Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

asp.net - Adding jQuery validator rules to dynamically created elements in ASP

I've got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can't (multiple fields in the UI generate the value for one hidden field - and this is what is submitted. We can't validate against a hidden field, so we must instead add UI-only validation for the fields the user can see)

Once the fields are dynamically added to the page, I run the following code over the container:

$container.find(".date").rules("add", {
    required: true,
    messages: {
        required: "The date is required"
    }
});

But it doesn't work! Oddly enough, disabling the above code, creating the dynamic elements, then running the code in the browser JS console works, but only the default validation message shows.

I'm at a loss. Any ideas?

I am using jQuery Validation 1.9.0 & the unobtrusive plugin

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As it turns out, this can be done mostly in HTML by adding a few attributes to each form element:

  • A name attribute
  • data-val="true"
  • data-val-required="message"

Like so:

<input type='text' name="date" data-val="true" data-val-required="A date is required." />

Then the form just needs to be re-parsed via JS:

//Remove current form validation information
$("form")
    .removeData("validator")
    .removeData("unobtrusiveValidation");

//Parse the form again
$.validator
    .unobtrusive
    .parse("form");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...