Reputation: 1
i am trying to validate my form for empty fields but i am not sure what code i should use can someone please direct me i have tried the following code but its not working
$("validate").submit(function(event){
$(".offset2").each(function(index) {
if ($(this).val() == 0) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
event.preventDefault();
}
});
});
Upvotes: 0
Views: 83
Reputation: 3659
@CodeMonkeyForHire suggested using a Plugin.
The most used one is jQueryValidation. It will let you write markup like this:
<input id="cname" name="name" minlength="2" type="text" required/>
And then on your submit button you make one single call to validate all elements inside the form:
$("#commentForm").validate();
There are many other frameworks like ParselyJs or ValidateJs that you can try out.
P.S. Google is your friend, always look for plugins (probably someone else had the same problem you did)
Upvotes: 0
Reputation: 12848
I would definitely recommend H5Validate http://ericleads.com/h5validate/
It allows you to use the proper HTML5 attributes for validation.
Upvotes: 0
Reputation: 3642
aren't you missing a "#" before "validate".
$("#validate").submit(function(event){
$(".offset2").each(function(index) {
if ($(this).val() == 0) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
event.preventDefault();
}
});
}
);
Upvotes: 0
Reputation: 993
Check this
if ($(this).val().length == 0) { // .length is missing in your code
// Show Error
}
// Or
if (!$(this).val()) { // Empty string is consider as false type in JavaScript
// Show Error
}
Upvotes: 1
Reputation: 362
Just use a plugin.... More flexibility as you grow.
Here's free one after 1 minute of google.
Upvotes: 1
Reputation: 40639
Try this,
$(function(){
$("validate").submit(function(event){
event.preventDefault();
var status=true;
$(".offset2").each(function(index) {
if (!$(this).val()) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
status=false;
}
});
return status;
});
});
Upvotes: 0