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
281 views
in Technique[技术] by (71.8m points)

Validate fields using JQuery validation without any submit?

I have a HTML5 web application with numerous user-entered fields, and I would like to do some client-side validation on those fields in javascript before sending them to the server. Easy right? Just use JQuery validation plugin --- http://jqueryvalidation.org/

But there's a catch. My web app has no forms. There is no submit anywhere in the HTML. Instead there's a JQuery change handler on every user-changeable element, and when the user changes the value of one of those element, an AJAX call is made. (This nonstandard user interaction architecture makes sense for this application.)

I would like to validate the field before the AJAX call, and use the JQuery validation plugin to do that. But I can't figure out how.

Is it possible to use the JQuery validation plugin without a submit anywhere? How would I do this? Or is another approach better?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Firstly, and most importantly, you must wrap your input elements inside <form></form> tags for the jQuery Validate plugin to operate. However, a submit button is not required.

Secondly, you can programatically trigger the validity test of any or all elements without a submit button by using the .valid() method.

$(document).ready(function() {

    $('#myform').validate({  // initialize the plugin on your form.
        // rules, options, and/or callback functions
    });

    // trigger validity test of any element using the .valid() method.
    $('#myelement').valid();

    // trigger validity test of the entire form using the .valid() method.
    $('#myform').valid();

    // the .valid() method also returns a boolean...
    if ($('#myform').valid()) {
        // something to do if form is valid
    }

});

DEMO: http://jsfiddle.net/URQGG/


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

...