10
votes

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.

1
FYI: Partial views doesn't mean that you have to refresh the whole view.Robert Koritnik
Can you expound? You'd at least have to refresh the part of the view bound to the model in question. I have some drop down boxes with a ton of items and I'm not terribly keen on rebuilding that and roundtripping the entire select listChris Cap
It would be easier if you'd provide the reply message (probably in a form of JSON) with validation errors. Then it would be easier for us to elaborate on the solution. So you make an Ajax request. Show us what gets back to the client...Robert Koritnik
I know I could do something like $('span[data-valmsg-for=Name').text(message) but that makes me a bit nervous, tinkering around with it that directly. I'm assuming/hoping that the html 5 property doesn't change. And then what would happen on subsequent validation if data annotations did trigger something. I'm going to test it out but it doesn't seem like a good solutionChris Cap
Did you find something that worked better for you? I am running into the same issue.AlexGad

1 Answers

17
votes

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

var validator = $("form").validate();
validator.showErrors({field : "Error Message"})