jjzjj

c# - MVVM - 验证真的需要这么麻烦吗?

coder 2024-05-27 原文

在我的应用程序中,我有大量的表单,其中大部分都有自己的绑定(bind)模型!当然数据验证很重要,但是没有比为所有模型实现 IDataErrorInfo 然后为所有属性编写代码来验证它们更好的解决方案了吗?

我已经创建了验证助手,它删除了很多实际的验证代码,但我仍然忍不住觉得我错过了一两个技巧!我可以补充一点,这是我在其中使用 MVVM 的第一个应用程序,所以我确信我在这个主题上还有很多东西要学习!

编辑:

这是我非常不喜欢的典型模型的代码(让我解释一下):

    string IDataErrorInfo.Error
    {
        get
        {
            return null;
        }
    }

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            return GetValidationError(propertyName);
        }
    }

    #endregion

    #region Validation

    string GetValidationError(String propertyName)
    {
        string error = null;

        switch (propertyName)
        {
            case "carer_title":
                error = ValidateCarerTitle();
                break;
            case "carer_forenames":
                error = ValidateCarerForenames();
                break;
            case "carer_surname":
                error = ValidateCarerSurname();
                break;
            case "carer_mobile_phone":
                error = ValidateCarerMobile();
                break;
            case "carer_email":
                error = ValidateCarerEmail();
                break;
            case "partner_title":
                error = ValidatePartnerTitle();
                break;
            case "partner_forenames":
                error = ValidatePartnerForenames();
                break;
            case "partner_surname":
                error = ValidatePartnerSurname();
                break;
            case "partner_mobile_phone":
                error = ValidatePartnerMobile();
                break;
            case "partner_email":
                error = ValidatePartnerEmail();
                break;
        }

        return error;
    }

    private string ValidateCarerTitle()
    {
        if (String.IsNullOrEmpty(carer_title))
        {
            return "Please enter the carer's title";
        }
        else
        {
            if (!ValidationHelpers.isLettersOnly(carer_title))
                return "Only letters are valid";
        }

        return null;
    }

    private string ValidateCarerForenames()
    {
        if (String.IsNullOrEmpty(carer_forenames))
        {
            return "Please enter the carer's forename(s)";
        }
        else
        {
            if (!ValidationHelpers.isLettersSpacesHyphensOnly(carer_forenames))
                return "Only letters, spaces and dashes are valid";
        }

        return null;
    }

    private string ValidateCarerSurname()
    {
        if (String.IsNullOrEmpty(carer_surname))
        {
            return "Please enter the carer's surname";
        }
        else
        {
            if (!ValidationHelpers.isLettersSpacesHyphensOnly(carer_surname))
                return "Only letters, spaces and dashes are valid";
        }

        return null;
    }

    private string ValidateCarerMobile()
    {
        if (String.IsNullOrEmpty(carer_mobile_phone))
        {
            return "Please enter a valid mobile number";
        }
        else
        {
            if (!ValidationHelpers.isNumericWithSpaces(carer_mobile_phone))
                return "Only numbers and spaces are valid";
        }

        return null;
    }

    private string ValidateCarerEmail()
    {
        if (String.IsNullOrWhiteSpace(carer_email))
        {
            return "Please enter a valid email address";
        }
        else
        {
            if (!ValidationHelpers.isEmailAddress(carer_email))
                return "The email address entered is not valid";
        }
        return null;
    }

    private string ValidatePartnerTitle()
    {
        if (String.IsNullOrEmpty(partner_title))
        {
            return "Please enter the partner's title";
        }
        else
        {
            if (!ValidationHelpers.isLettersOnly(partner_title))
                return "Only letters are valid";
        }

        return null;
    }

    private string ValidatePartnerForenames()
    {
        if (String.IsNullOrEmpty(partner_forenames))
        {
            return "Please enter the partner's forename(s)";
        }
        else
        {
            if (!ValidationHelpers.isLettersSpacesHyphensOnly(partner_forenames))
                return "Only letters, spaces and dashes are valid";
        }

        return null;
    }

    private string ValidatePartnerSurname()
    {
        if (String.IsNullOrEmpty(partner_surname))
        {
            return "Please enter the partner's surname";
        }
        else
        {
            if (!ValidationHelpers.isLettersSpacesHyphensOnly(partner_surname))
                return "Only letters, spaces and dashes are valid";
        }

        return null;
    }

    private string ValidatePartnerMobile()
    {
        if (String.IsNullOrEmpty(partner_mobile_phone))
        {
            return "Please enter a valid mobile number";
        }
        else
        {
            if (!ValidationHelpers.isNumericWithSpaces(partner_mobile_phone))
                return "Only numbers and spaces are valid";
        }

        return null;
    }

    private string ValidatePartnerEmail()
    {
        if (String.IsNullOrWhiteSpace(partner_email))
        {
            return "Please enter a valid email address";
        }
        else
        {
            if (!ValidationHelpers.isEmailAddress(partner_email))
                return "The email address entered is not valid";
        }
        return null;
    }

    #endregion

用一个 switch 语句来识别正确的属性,然后必须为每个属性编写唯一的验证函数的想法感觉太多了(不是在工作量方面,而是在所需的代码量方面)。也许这是一个优雅的解决方案,但它就是不像一个解决方案!

注意:我将按照其中一个答案中的建议将我的验证助手转换为扩展(感谢 Sheridan)

解决方案:

所以,按照我接受的答案,这是我为让它最初工作而实现的基本框架(显然我会改进部分 - 但我只是想先让它开始,因为我没有使用 lambda 的经验实现之前的表达或反射(reflection))。

Validtion Dictionary 类(显示主要功能):

    private Dictionary<string, _propertyValidators> _validators;
    private delegate string _propertyValidators(Type valueType, object propertyValue);


    public ValidationDictionary()
    {
        _validators = new Dictionary<string, _propertyValidators>();
    }

    public void Add<T>(Expression<Func<string>> property, params Func<T, string>[] args)
    {
        // Acquire the name of the property (which will be used as the key)
        string propertyName = ((MemberExpression)(property.Body)).Member.Name;

        _propertyValidators propertyValidators = (valueType, propertyValue) =>
        {
            string error = null;
            T value = (T)propertyValue;

            for (int i = 0; i < args.Count() && error == null; i++)
            {
                error = args[i].Invoke(value);
            }

            return error;
        };

        _validators.Add(propertyName, propertyValidators);
    }

    public Delegate GetValidator(string Key)
    {
        _propertyValidators propertyValidator = null;
        _validators.TryGetValue(Key, out propertyValidator);
        return propertyValidator;
    }

模型实现:

public FosterCarerModel()
    {
        _validationDictionary = new ValidationDictionary();
        _validationDictionary.Add<string>( () => carer_title, IsRequired);
    }

    public string IsRequired(string value)
    { 
        string error = null;

        if(!String.IsNullOrEmpty(value))
        {
            error = "Validation Dictionary Is Working";
        }

        return error;
    }

IDataErrorInfo 实现(模型实现的一部分):

string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            Delegate temp = _validationDictionary.GetValidator(propertyName);

            if (temp != null)
            {
                string propertyValue = (string)this.GetType().GetProperty(propertyName).GetValue(this, null);
                return (string)temp.DynamicInvoke(typeof(string), propertyValue);
            }                

            return null;
        }
    }

忽略我草率的命名约定和地方编码,我很高兴能让它工作!当然要特别感谢 nmclean,还要感谢为这个问题做出贡献的每个人,所有回复都非常有帮助,但经过一番考虑后我决定采用这种方法!

最佳答案

我使用 extension 方法来减少我必须编写的验证文本的数量。如果您不熟悉它们,请查看 Extension Methods (C# Programming Guide) MSDN 上的页面以了解有关 extension 方法的信息。我有几十个这样的验证每一种情况。例如:

if (propertyName == "Title" && !Title.ValidateMaximumLength(255)) error = 
    propertyName.GetMaximumLengthError(255);

Validation.cs 类中:

public static bool ValidateMaximumLength(this string input, int characterCount)
{
    return input.IsNullOrEmpty() ? true : input.Length <= characterCount;
}

public static string GetMaximumLengthError(this string input, int characterCount, 
    bool isInputAdjusted)
{
    if (isInputAdjusted) return input.GetMaximumLengthError(characterCount);
    string error = "The {0} field requires a value with a maximum of {1} in it.";
    return string.Format(error, input, characterCount.Pluralize("character"));
}

请注意,Pluralize 是另一种扩展 方法,如果输入值不等于 1,它会在输入参数的末尾简单地添加一个“s”。另一种方法可能是:

public static bool ValidateValueBetween(this int input, int minimumValue, int 
    maximumValue)
{
    return input >= minimumValue && input <= maximumValue;
}

public static string GetValueBetweenError(this string input, int minimumValue, int 
    maximumValue)
{
    string error = "The {0} field value must be between {1} and {2}.";
    return string.Format(error, input.ToSpacedString().ToLower(), minimumValue, 
        maximumValue);
}

当然,实现您需要的所有方法需要一些时间,但之后您将节省大量时间,并且您将获得所有错误消息保持一致的额外好处。

关于c# - MVVM - 验证真的需要这么麻烦吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18869235/

有关c# - MVVM - 验证真的需要这么麻烦吗?的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  5. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  6. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

  7. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  8. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  9. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  10. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

随机推荐