mvc3 validate input 'not-equal-to'

后端 未结 6 1532
滥情空心
滥情空心 2020-12-13 21:33

My forms have inputs with default helper text that guides the user on what to enter (rather than using labels). This makes validation tricky because the input value is never

6条回答
  •  余生分开走
    2020-12-13 21:56

    Here's a sample illustrating how you could proceed to implement a custom validation attribute:

    public class NotEqualAttribute : ValidationAttribute, IClientValidatable
    {
        public string OtherProperty { get; private set; }
        public NotEqualAttribute(string otherProperty)
        {
            OtherProperty = otherProperty;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(OtherProperty);
            if (property == null)
            {
                return new ValidationResult(
                    string.Format(
                        CultureInfo.CurrentCulture, 
                        "{0} is unknown property", 
                        OtherProperty
                    )
                );
            }
            var otherValue = property.GetValue(validationContext.ObjectInstance, null);
            if (object.Equals(value, otherValue))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "notequalto",
            };
            rule.ValidationParameters["other"] = OtherProperty;
            yield return rule;
        }
    }
    

    and then on the model:

    public class MyViewModel
    {
        public string Prop1 { get; set; }
    
        [NotEqual("Prop1", ErrorMessage = "should be different than Prop1")]
        public string Prop2 { get; set; }
    }
    

    controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel
            {
                Prop1 = "foo",
                Prop2 = "foo"
            });
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    and view:

    @model MyViewModel
    
    
    
    
    
    @using (Html.BeginForm())
    {
        
    @Html.LabelFor(x => x.Prop1) @Html.EditorFor(x => x.Prop1) @Html.ValidationMessageFor(x => x.Prop1)
    @Html.LabelFor(x => x.Prop2) @Html.EditorFor(x => x.Prop2) @Html.ValidationMessageFor(x => x.Prop2)
    }

提交回复
热议问题