简体   繁体   中英

AJAX validation on simple form

I am trying to do client-side validation using AJAX to check for empty fields on a simple form. If the field is empty, I want to notify the user that this is not valid. The form should not submit if there are any empty fields.

What's the best way to do this?

Ajax is not required to do client-side validation. I can only assumed you're interchanging the term with "jQuery". In that case...

jQuery Validate is, by far, the mostly widely used jQuery validation plugin.

"The plugin is written and maintained by Jörn Zaefferer, a member of the jQuery team, lead developer on the jQuery UI team and maintainer of QUnit. It was started back in the early days of jQuery in 2006, and updated and improved since then."

Here is a working demo...

http://jsfiddle.net/EggSb/

jQuery:

$(document).ready(function() {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                minlength: 5,
                // other rules
            },
            field2: {
                required: true,
                email: true,
                // other rules
            }
        }
    });

});

HTML:

<form id="myform">  
     <input type="text" name="field1" />
     <input type="text" name="field2" />
     <input type="submit" />
</form>

There's no need to use AJAX if all you are testing for is empty fields. If you are targeting browsers that support HTML5 forms you can just do:

<input type="text" name="username" required />

If you are required to support other browsers like IE you will need to use JavaScript. Google "JavaScript form validation library" to find examples of JavaScript to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM