In ASP.NET MVC Unobtrusive validation MaxLength , Range Data annotation attributes are evaluated eagerly. Is there a way to defer that during submit button and show validation error messages on Validation Summary ?
[MaxLength(5, ErrorMessage = "zip code length can not be greater than 5")]
public string ZipCode { get; set; }
This suppose is evaluated on tab index change.
There are many options you can turn on/off.
Code below will not perform validation when focus leaves the control. I have added 2 other options just so you can see they are also avaialable but commented them out:
$('#your-control-id').validate({
onfocusout: false//,
//onkeyup: false,
//onclick: false
});
Related
I have a model that includes the following property:
[Required]
public string City { get; set; }
Basically, a user selects a stored value from a dropdown. The fields in my partial view are populated with the corresponding data. In certain circumstances, the stored data will not have a value for City. I am trying to use jQuery to check that if the field is empty, to basically not require the field and to allow submission. I have tried the following:
$("#City").attr("data-val", "false");
$("#City").rules("remove", "required");
$("#City").attr("disabled", "disabled");
$("#City").attr("aria-required", "false");
$("#City").removeAttr("required");
None of these work. On submit, the proper method is hit in the controller with a ModelState.IsValid of false and an error stating that "The City field is required."
How can I use jQuery to prevent this field from being validated on submit?
Before checking whether the ModelState.IsValid, you can remove the errors on that property of the Model ModelState["City"].Errors.Clear(); Therefore meaning regardless of what errors have occurred on your City property, the model state will be valid.
Note, this fix should be applied in the controller on the server - it is not related to jQuery.
Even though there were some great suggestions from posters, I ended up reevaluating our needs and found that the Required attribute was not required for that specific property.
Thanks for your suggestions everyone.
Could someone provide a good tutorial on how may I validate my html fields with unobtrusive,
but without using MVC helpers.
Is it possible at all?
I would like to keep the plain html and use input type="text" field instead of mvc helpers <%= Html.TextBox("Name") %> but still using the model validation..
public class Employee
{
[Required]
public string Name { get; set; }
}
Also is it possible with jquery Ajax?
Thanks
While it is possible to perform unobtrusive validation in MVC without using helpers, it will be painfully for you as developer to do it manually without usage of mvc helpers. Saying strictly, it will kill your performance and make your code unreadable.
Basically, unobtrusive validation consists of two parts: server side, via data-attributes to your model fields and MVC Helpers, which generate necessary markup, and client side library, jquery.validate.unobtrusive.js, which parses those markup to meaningful parts for jquery validate plugin.
So, in general, you can manually write necessary markup, as long as validation js library will be loaded, validation will work. For example, field, which is subject of validation, must be marked with data-val='true' attribute. If you want to make your field required, you should write additionally something like data-val-required="error message". For length validation - data-val-length-min="5" (obviously, minimum) data-val-length-max="50" (maximum length), data-val-length="Min 5 max 50 chars required".
While, when using normal mvc approach, it is just a question of model attribute:
[Required]
[StringLength(50, MinimumLength = 5)]
public string Name { get; set; }
and one line of code in markup:
#Html.TextBoxFor(o=>o.Name)
Nice, shiny, separates View and Model, and helps KISS.
And for second part of your question. If I understood your problem correctly, you want to validate dynamic forms. Probably it will be answer:
jquery.validate.unobtrusive not working with dynamic injected elements
I have the following property on my viewmodel:
[Required(ErrorMessage = "Email is required")]
[RegularExpression(RegularExpressions.Email, ErrorMessage = "Email is not valid")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
In MVC4, because of the DataType annotation, this is rendered as <input type="email"... which is great for devices that change the keyboard to include # such as the ipad. Unfortunately, jquery.validate seems to automatically validate the field using its own regex so if a user enters an incorrect email, the jquery validate error message is shown and not the one I defined in the attribute.
What is the best way to stop jquery.validate doing this automatic validation so that my regex is used instead?
In short the answer for this is that MVC does not support automatically overriding JQuery validation message, or suppressing the validation.
However you can relatively easily localize the JQuery validation. Here are a few examples of how to do that:
How to change JQuery validation text directly
JQuery validation localization plug in
** Warning - I have not tested these myself, but in general you want to include your scripts right after the JQuery reference on your page
Found this answer by Dave Ward suggesting a workaround which does not involve changing external js libraries.
Just add the following after your jquery and jquery.validate includes:
$.validator.methods.email = function (value, element) {
return this.optional(element) || true; };
I'm using ASP.NET MVC 3 + FLUENT VALIDATION + NINJECT
I have model X and rules for that model are something like this:
RuleFor(c => c.FirstName).NotEmpty();
RuleFor(c => c.LastName).NotEmpty();
I spotted a little strange thing, the engine puts validation attributes on all hidden elements and on dropdowns, radio buttons, etc.., and I didn't specified this in the validation configuration for that model, so I guess it is by default...
<input type="hidden" value="1" name="Id" id="Id" data-val-required="'Id' must not be empty." data-val-number="The field Id must be a number." data-val="true">
Validation works because hidden element always have a value, but I have a problem with radio buttons. For example, if I don't want one radio button always to be selected by default but empty and if I want to put validation rules on that item, the rendering puts default validation attributes and on top of my rules, so it's getting messed up and validation doesn't work properly...
Anyone had similar issues or knows about this, or do I have to pull the ASP.NET MVC source and look it up by myself? :)
Semi-Lazy and little-pushed-down-by-deadlines coder
Edit:
I tried proposed solution from this link:
Fluent Validations. Error: Validation type names in unobtrusive client validation rules must be unique
but asp.net mvc emits required attributes on each field regardless of AddImplicitRequiredAttribute settings...
Make the Id property on your view model a nullable integer.
So instead of:
public int Id { get; set; }
you should use:
public int? Id { get; set; }
Same stands true for any other value types that you don't want to be required. You should use nullable types.
Html helpers automatically emit data-val attributes for all non-nullable types which is by design and if you do not want this behavior you will have to write your own custom HTML helpers to generate your input fields and dropdowns. You can no longer rely on TextBoxFor and DropDownListFor helpers as that's how they are designed.
I'm stuck with ASP.NET MVC 3 jQuery unobtrusive validation message localisation. Specifically with "number" validation. If I have a number property in model input html is rendered with data-val-number attribute with value "The field Quantity must be a number." How I can localize this string. With data annotation attributes there is no problem to define localized message. But for number validation I do not have to specify any attribute.
So, how can be localized validation messages generated by unobtrusive validation?
I got to solution refering this article http://jwwishart.wordpress.com/2010/03/22/custom-server-and-client-side-required-validator-in-mvc-2-using-jquery-validate/
It works, but still very unconvenient.
If there is only one culture it could be convenient to use
$('input[data-val-number]').attr('data-val-number', 'Custom message');
This script must go before
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Found something. This blog explains step by step how to accomplish this. I just tried a quick run through using MVC 3 unobstructed validation and it worked perfect.
Basically, you add a resource, and use validation attribute like this:
[Range(1, 130, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "Range")]
public string myNumber { get; set; }
The result was client validation with my custom string.