1

我有一个实现自定义验证器的 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,我该怎么做?

4

1 回答 1

2

这是我在这种情况下会做的事情:(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# 中完成的验证并将结果传递回您的视图。

于 2013-09-09T13:43:26.603 回答