asp.net mvc 3 jquery adding validation message manually - asp.net-mvc-3

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.

I had exactly the same requirement, I actually found the following method.
var validator = $("form").validate();
validator.showErrors({field : "Error Message"})

Related

Where i need to put validation code?

I have a form with a number of fields.
Some of them are userId, userFirstName, userLastName.
When user inputs incorrect userId value then near userId field page must show error message and add this error into validationSummary(this is standart behavior for asp.net mvc unobtrusive validation). If userId is correct then page must remove errors and autopopulate userFirstName and userLastName(This is not standart behavior)
How can i implement this?
Here is what come to my mind:
Remote validation attribute
It has a bad customization in my case. That's why i decide to don't use it.
Add special method for jquery validation plugin ( for example
jQuery.validator.addMethod("userIdValidation", function(value, element) {
//some logic
return something;
}, "Please specify the correct userId"); )
and put there logic for validation and for autopopulate other fields.
In this case i mix validation and other stuff.
3 . Add special method for jquery validation plugin ONLY for validation and add special handler for input change event for autopopulate.
In this case i need to send TWO ajax requests to server for one thing. And ofcourse it is not good too. So what is the right way? I am confused.
Have you thought about using a partial view to display the userFirstName and userLastName?
You can fire an AJAX request that sends the userId, and then returns a partial view of the name fields. Within the controller being called, you can validate the incoming userId, and then grab the name details in one query. If thevalidation fails, you can return the partial view with empty fields.

input validation not working on asp.net mvc 4 model sent as JSON

I have a model and a form in the view. I have a simple field of string which is called description. I'm able to insert scripts like: <script>alert('xss')</script> to that field.
I can see that in other actions on my site with other models I can't
I do not have an AllowHtml or anything like that.
the only difference is that for this model I use a post with a json object and content-type of application/json
the ModelState.IsValid is returning true. even though there is a description property with an xss script on it...
and for the other actions I make a simple ajax post.
why isn't the validation input work on this kind of JSON ajax posts?
how can I prevent xss across the entire site for this kind of ajax requests?
thanks
It is because ValidateInput is only for FormValueProvider. As for JsonValueProvider, you need to roll out your own mechanism.
Steps
1) Create a marker attribute CustomAntiXssAttribute
2) Create a custom model binder by sub-classing DefaultModelBinder
3) Overrides BindProperty method -> get the attempted value for the underlying property, sanitize it and assign it to the view model property.
Check this out.
Edited:
Replace the line var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); with var valueResult = bindingContext.ValueProvider.GetValue((string.IsNullOrWhiteSpace(bindingContext.ModelName) ? string.Empty : bindingContext.ModelName + ".") + propertyDescriptor.Name); in order to support nested ViewModel.
try using AntiXssLibrary from Nuget, and by using getSafeHtmlContent. you can get the safe content while you're saving your records to db.
Another approach is to use a Sanitizer library like this one, you can choose which HTML tags you want to be filtered out.

Displaying model state errors after ajax call on Razor views

I have razor view with #Html.ValidationMessageFor helpers and jquery unobtrusive validation setup.
I want to call controller/action and to show eventual model state errors returned by action by using same validation logic that is already set in place.
I've made some code that does it but I was wondering if there is already way to do it automatically, i.e. if I capture HTTP Bad Request as AJAX response, I want to take out model state errors from response body and plug them in to unobtrusive validation.
I'm looking for complete recommended solution, not workarounds :)
Thanks!
You can return errors with Json result (How to get all Errors from asp.net mvc modelState?):
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
Then manually show errors. Get form validator:
var validator = $("form").validate();
Then check that your fields are initialized correctly, for example you can look here (optional step):
validator.settings.rules
OR
validator.settings.messages
If everything is fine, then you could show error:
validator.showErrors({"Password": "Too simple!"});
Where Password is field name and Too simple! is error message.

Real-Time Validations in Backbone-Forms

I am using Backbone-Forms and have created a model with the following schema:
schema:
title:
type: "Text"
validators: ["required"]
description:
type: "TextArea"
validators: ["required"]
location:
type: "Text"
validators: ["required"]
When I try and submit the form with empty fields, the validation correctly takes place and they all receive the error class.
However, when I then update an input to have content, the error class doesn't get removed from my input until I try and submit the form again.
Likewise, if I originally enter a valid input and then delete all content, it doesn't inform me of an error until I try and submit the form again whereas I would like to know immediately.
Is there a way to trigger validation on a modified input field?
From the docs: http://backbonejs.org/#Model-validate:
isValidmodel.isValid()
Models may enter an invalid state if you make changes to them silently ... useful when dealing with form input. Call model.isValid() to check if the model is currently in a valid state, according to your validate function.
also from https://github.com/thedersen/backbone.validation#what-gets-validated-when
What gets validated when?
If you are using Backbone v0.9.1 or later, all attributes in a model will be validated. However, if for instance name never has been set (either explicitly or with a default value) that attribute will not be validated before it gets set.
This is very useful when validating forms as they are populated, since you don't want to alert the user about errors in input not yet entered.
If you need to validate entire model (both attributes that has been set or not) you can call validate() or isValid(true) on the model.
The Backbone-Forms docs specifically mention model.validate:
https://github.com/powmedia/backbone-forms#model-validation
You could easily hook model.Validate up to whatever edit events or click events you want.
Also, you might find this useful (not sure if it is compatible with Backbone.Forms though):
https://github.com/thedersen/backbone.validation
The way you can do "Real-Time Validations" with Backbone-Forms is by extending the Backbone.Form model and attaching event(s) to call your custom method(s) to validate the field, then just "new"ing your custom form instead of Backbone.Form
(Backbone.Form is just a subclass of Backbone.View)
Here's some sample code:
var MyCustomForm = Backbone.Form.extend({
events: {
"blur input": "validateRealTime"
},
validateRealTime: function(e){
if(e.currentTarget.value == "") return;
var err = this.fields[e.currentTarget.name].validate();
if(err)
myDisplayErrorMethod(err.message);
}
});
The great thing about this is that it'll utilize the validators you defined in the model schema so you get all the same validations and messages you defined there as well (if you actually did define custom mesesages).
Also if you defined several validators as I did, each time the user "blur"s from the field, it'll call your validators in order until all validators pass. So that was a plus.
Side note, you'll notice I did if(e.currentTarget.value == "") return;. That's just my use case, I didn't want to show errors just because users clicked and clicked away.

Validate data from CakePHP form with jQuery (AJAX)

I would like to validate both single field and multiple field data from a CakePHP form.
The single field validation should be done on blur from each field while the multiple field validation should be done on submitting the form.
I would like to use the $validate property declared in the Model for validating data and I would like to display the errors near each field (single field validation) and on top of the form (for multiple field validation).
My main goal is to achieve this the most "caky" way (if there is one for validating data with jQuery). I couldn't find any useful advice out there and I'm asking you for some help to get this going.
One of my concerns is how shall I pass data from the form to jQuery and then to the action that does the validation and also how shall I return and display the errors, if there are any.
Thank you in advance!
I'd suggest first making sure everything works without jQuery, then use the jQuery Form plugin to submit your forms via AJAX. If you include the RequestHandler component in your AppController, you should find that your controllers distinguish automatically between AJAX and synchronous requests.
OK, so I coded my own solution to this, but I am still waiting for a more "caky" approach.
I made two generic jQuery functions, one for single field validation and one for multiple field validation. The function should grab the data from the specified form and send it to the form's action via AJAX, to a specially created controller method which will attempt to validate data and output an AJAX response ("" for validation has passed and errors for errors in validation). Then, the result is checked in the jQuery function and the default form behaviour is triggered only if the validation has passed. Otherwise, display the errors and return false; to prevent default submission.

Resources