Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding validation with MVC 3 & jQuery Validator in execution time

I have a form with validation rendered by c# when the page is loaded, the rendered fields like so:

<input autocomplete="off" class="input-validation-error" data-val="true" data-val-number="The field Idade must be a number." data-val-range="message here" data-val-range-max="25" data-val-range-min="16" data-val-required="The Idade field is required." id="Content_MyFieldId" maxlength="3" name="Content.MyFieldId" value="0" type="text">

and I'm trying put a new html object equals the example with jQuery, but this new field is not validated when I submit the form.

Have a way to add validation in this field using jQuery?

PS: I don't want to use manual method like so:

$("#field").rules("add", {
    required: true,
    messages: {
        required: "Required input"
    }
});

Because I have the rules in the input field, I only want to apply it.

like image 828
Cesar Avatar asked Feb 24 '11 11:02

Cesar


People also ask

How can we implement validation in MVC?

Adding Validation to ModelThe validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation.

Where does validation go in MVC?

Validation should be in the domain layer, but it can also be used in other layers, like the UI (probably in the Controller or the View in Js) to give fast feedback to the user.


2 Answers

Feels like a bit of a hack, but here's how I've done it.

// Target Form
var $form = $("**form selector**");

// Unbind existing validation
$form.unbind();
$form.data("validator", null);

// Check document for changes
$.validator.unobtrusive.parse(document);

// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);

Rich

like image 154
kim3er Avatar answered Sep 25 '22 01:09

kim3er


I solved here using

jQuery.validator.unobtrusive.parseElement($("#element")[0], false);
$.validator.unobtrusive.parseDynamicContent($("#element")[0]);

parseDynamicContent I got here

like image 41
Zote Avatar answered Sep 23 '22 01:09

Zote