Search code examples
asp.net-mvc-4unobtrusive-javascriptjquery-validate

Getting the message from jquery validation when using UnobtrusiveJavaScript


Hey there StackOverflow enthusiasts.

I am attempting to update an old site of mine to the newest edition of Asp.net MVC4. It was previously on MVC2, and on MVC2 it allowed me to pretty much separate my jquery and client side stuff from any of the backend stuff. But I guess with MVC4 they want you to have a lot of your validation stuff tied directly to your models and so on.

But I have a client side jquery validation script that was working pretty well before, and I was wondering, how can I get it to work again. Specifically, I had a field that would not be validated if the user entered in more than 4000 characters. Otherwise it would not be required. Here is the client side code that worked before in MVC2....

Comment: {
    required: function (element) {
    return $(element).val().length > 4000;
    },
    maxlength: 4000
}

and the message that would be displayed if validation was not passed...

messages: {
                ...
                Comment: 'Why dont you stop attempting to put in more than 4000 characters?  Thanks...'
            }

How can I do that with MVC four? To get anything to display in another field I noticed I needed to put a required over the field in my model...

    [Required(ErrorMessage = "Please select an Admit Date")]
    public DateTime? AdmitDate { get; set; }

Is there a way to write a requirement function so that it is only required under certain circumstances? I would prefer to keep it client side to keep my concerns separate if you know what I mean. Any help would be appreciated.


Solution

  • You can use [Required] and [StringLength] to constrain the input on your Comment.

    [Required(ErrorMessage = "Please fill in a comment")]
    [StringLength(4000, ErrorMessage = "Why dont you stop attempting to put in more than 4000 characters?  Thanks...")]
    public string Comment { get; set; }
    

    Conditional required constraints are not covered by default data annotations. The default way of handling 'complex' validations is by implementing the IValidatableObject interface on your model.

    However, since you are looking for a client-side solution, we can look at other frameworks that may solve this problem for you. For instance, MVC Foolproof Validation supports a [RequiredIf] attribute that also works client-side.