Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 3 jquery adding validation message manually

I've been search for quite a while and haven't been able to find an answer to this.

I am using asp.net MVC 3 with unobtrusive validation. My model is bound with data annotations for simple validation (required fields, regex, etc..). However, I have more complex validation that occurs on the server. I'm doing an ajax post which returns me validation add'l messages that come from my domain model. All I want to do is put those validation messages on the form in the place of the existing ones. I don't want to use partial views since all I've really got are messages coming back and there isn't a need to refresh the whole view. Also, I'm not adding new rules or new inputs to the form so $.validator.unobtrusive.parse won't work. These are just messages I want to put on the form. The $.post call returns a list of message with which field is/was affected and the validation message.

Here's kind of what I'm looking to do

 $.post(url, { someData}, function (data) {
         for (message in data.Messages) {
             $("#form").validate().addMessage(message.Field, message.Text);
         }
    });

Thanks for your help

Per request, here's a sample of the returning JSON, it's fairly simple.

{"id":0,"messages":["Level":0,"Message":"Style is required","Name":"Style"}],"operationResult":false}

messages is a list of objects that contain the severity level, the property the error belonged to and the error message. I would use the name in the messages object to match where it want on the form.

like image 234
Chris Cap Avatar asked May 18 '11 17:05

Chris Cap


1 Answers

I had exactly the same requirement, I actually found the following method.

var validator = $("form").validate();
validator.showErrors({field : "Error Message"})
like image 148
Rohan West Avatar answered Nov 13 '22 16:11

Rohan West