Group validation messages for multiple properties together into one message asp.net mvc

前端 未结 4 1357
失恋的感觉
失恋的感觉 2020-12-10 03:19

I have a view model that has year/month/day properties for someone\'s date of birth. All of these fields are required. Right now, if someone doesn\'t enter anything for the

4条回答
  •  长情又很酷
    2020-12-10 04:00

    You should implement IValidatableObject and take of the Require. Then the validation on the server side will do the job, something like:

    public class MyModel : IValidatableObject
    {
      public int Year { get; set; }
      public int Month { get; set; }
      public int Day { get; set; }
    
      public IEnumerable Validate(ValidationContext validationContext)
      {
          if (/*Validate properties here*/) yield return new ValidationResult("Invalid Date!", new[] { "valideDate" });
      }
    }
    

    For client side validation you need to implement your own function, and prompt the error to the user somehow.

    EDIT: Given that you still need client side validation, you should do something like this:

    $("form").validate({
        rules: {
            Day: { required: true },
            Month : { required: true },
            Year : { required: true }
        },
        groups: {
            Date: "Day Month Year"
        },
       errorPlacement: function(error, element) {
           if (element.attr("id") == "Day" || element.attr("id") == "Month" || element.attr("id") == "Year") 
            error.insertAfter("#Day");
           else 
            error.insertAfter(element);
       }
    });
    

提交回复
热议问题