Reputation: 3
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?
Upvotes: 0
Views: 408
Reputation: 98748
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...
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>
Upvotes: 1
Reputation: 44959
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.
Upvotes: 0