【问题标题】:validate a field in the viemodel before submit mvc在提交 mvc 之前验证 viemodel 中的字段
【发布时间】:2013-09-09 13:39:29
【问题描述】:

我有一个实现自定义验证器的 viewModel:

 public class RegistrationViewModel
{
    #region country
    public int CountryId { get; set; }
    public List<SelectListItem> Countries { get; set; }
    public ConfigurationParamValue CountryParam { get; set; }
    #endregion

    #region civilty
    [CivilityValidator(DependantField = "CivilityParam", Category = "Category", IsLocal = "IsLocal")]
    public int Civility { get; set; }
    public ConfigurationParamValue CivilityParam { get; set; }
    public List<SelectListItem> Civilities { get; set; }
    #endregion

    #region fistname
    [FirstNameValidator(DependantField = "FirstNameParam", Category = "Category", IsLocal = "IsLocal")]
    public string FirstName { get; set; }
    public ConfigurationParamValue?FirstNameParam { get; set; }
    #endregion

}

这是 firstName 的验证器:

 public class FirstNameValidator : BaseValidator,IClientValidatable
{
    private readonly IRegistrationConfiguration _registrationConfiguration;
    public string Category { get; set; }
    public string IsLocal { get; set; }
    public string DependantField { get;set; }
    public FirstNameValidator()
    {
        _registrationConfiguration = DependencyResolver.Current.GetService<IRegistrationConfiguration>();

    }
    public FirstNameValidator(IRegistrationConfiguration registrationConfiguration, IVpSpeedResourceProvider resourceProvider, IMemberContext memberContext)
    {
        _registrationConfiguration = registrationConfiguration;
        ResourceProvider = resourceProvider;
        MemberContext = memberContext;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        object dependantPropertyValue=null;
        string categoryPropertyValue = string.Empty;
        bool isLocalPropertyValue = false;
        if (validationContext != null)
        {
            if (DependantField != null)
            {
                PropertyInfo dependantProperty = validationContext.ObjectInstance.GetType()
                    .GetProperty(DependantField);

                dependantPropertyValue = dependantProperty
                                           .GetValue(validationContext.ObjectInstance, null);
            }

            PropertyInfo categoryProperty = validationContext.ObjectInstance.GetType()
                .GetProperty(Category);

           categoryPropertyValue = (string)categoryProperty
                                      .GetValue(validationContext.ObjectInstance, null);

           PropertyInfo isLocalProperty = validationContext.ObjectInstance.GetType()
               .GetProperty(IsLocal);

           isLocalPropertyValue = (bool)isLocalProperty
                                     .GetValue(validationContext.ObjectInstance, null);

        }


            if (value == null)
            {
                if(dependantPropertyValue != null && !((ConfigurationParamValue)dependantPropertyValue == ConfigurationParamValue.IsMandatory))
                    return ValidationResult.Success;
                return new ValidationResult(GetResource(isLocalPropertyValue, categoryPropertyValue, Constantes.FirstNameEmptyError));
            }
            {
                if (string.IsNullOrEmpty(value.ToString()))
                    return new ValidationResult(GetResource(isLocalPropertyValue, categoryPropertyValue, Constantes.FirstNameEmptyError));
                if (value.ToString().Length < _registrationConfiguration.FirstNameFieldMinLength)
                    return new ValidationResult(GetResource(isLocalPropertyValue, categoryPropertyValue, Constantes.FirstNameMinLengthError));
                if (value.ToString().Length > _registrationConfiguration.FirstNameFieldMaxLength)
                    return new ValidationResult(GetResource(isLocalPropertyValue, categoryPropertyValue, Constantes.FirstNameMaxLengthError));
            }

         return ValidationResult.Success;

    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
                            ControllerContext context)
    {

        var viewModel = (RegistrationViewModel)context.Controller.ViewData.Model;
        var rule = new ModelClientValidationRule();
        rule.ValidationParameters.Add("min", _registrationConfiguration.FirstNameFieldMinLength);
        rule.ValidationParameters.Add("max", _registrationConfiguration.FirstNameFieldMaxLength);
        rule.ValidationParameters.Add("mandatory", (viewModel.FirstNameParam == ConfigurationParamValue.IsMandatory ? true : false));
        rule.ValidationParameters.Add("emptyerror", GetResource(viewModel.IsLocal, viewModel.Category, Constantes.FirstNameEmptyError));
        rule.ValidationParameters.Add("minerror", GetResource(viewModel.IsLocal, viewModel.Category, Constantes.FirstNameMinLengthError));
        rule.ValidationParameters.Add("maxerror", GetResource(viewModel.IsLocal, viewModel.Category, Constantes.FirstNameMaxLengthError));
        rule.ValidationType = "firstnamevalidator";
        yield return rule;
    }
}

当我创建视图模型时,我从查询字符串中读取参数:

public ActionResult Index()
        {
   RegistrationViewModel ViewModel=new RegistrationViewModel();
  var firstName = Request.QueryString["FirstName"];
            if (!string.IsNullOrEmpty(firstName))
            {
                VieWmodel.FirstName = firstName;
            }
  return View(ViewModel);}

所以我只需要在返回视图之前验证属性 FirstName,我该怎么做??

【问题讨论】:

  • 我想在代码 c# 中执行此操作,如果名字有效,我保留值 else firstname=string.empty

标签: c# asp.net-mvc validation asp.net-mvc-4 asp.net-mvc-viewmodel


【解决方案1】:

这是我在这种情况下会做的事情:(W/jquery 和不显眼的验证)

由于我没有看到你的观点,所以我为你的表格起了个名字:

Edid:如果您只想验证单个字段,请在 before.valid() 之前传递 ID

   <script type="text/javascript">
        $("#CreateForm").submit(function (e) {
            if (!$("#FirstName").valid()) {
                alert('An Error has been detected on the page. Please correct and resubmit.');
                e.preventDefault();
            }
        });
    </script>

这将调用您在 C# 中完成的验证并将结果传递回您的视图。

【讨论】:

  • 我想在代码 c# 中执行此操作,如果名字有效,我保留值 else firstname=string.empty
  • 我将验证所有表单,我只需要验证字段名
  • 将您需要验证的字段传递到 .valid()...查看编辑。
猜你喜欢
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多