What is the best JQuery way to ensure that all input fields with the attribute "required" are completed
10 Answers
Use the .filter() method to check the value of each and then check the length property of the result:
var incomplete = $("input[required]").filter(function () {
return this.value === "";
});
if (incomplete.length) {
alert("Please fill in all the required fields");
}
Note that an attribute named required will invalidate your HTML. data-required would be valid HTML5, however, or you could just give them all a class and use that as the selector (which would also be more efficient).
You could also use one of the validation plugins out there: http://google.com/search?q=jquery+validation.
2 Comments
data-required for valid HTML5, without data- it's still invalid ;-)The best JQuery validation plugin is: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
(At least the one I use and feel most comfortable with)
Comments
There is also a plugin called 'valididty' that is worth a mention and is simpler to use IMO that the validation plugin.
Comments
You can also try bValidator plugin (http://code.google.com/p/bvalidator/) for form validation
Comments
Just add two attributes at the end of your input tags:
required="required" js-name="name_to_be_displayed"
<script language="javascript" src="jquery.min.js"></script>
<script language="javascript" type="application/javascript">
$(function (){
$("#submit").click(function (){
$('input').each(function(index, value) {
var attb = $(this).attr('required');
var value = $(this).val();
if (attb == "required" && value == "") {
alert($(this).attr('js-name') + " " + 'value required');
$(this).focus();
return false;
}
});
});
});
</script>
<form action="index.php" method="post" enctype="multipart/form-data" target="_self">
<label> Name:
<input name="Name:" type="text" size="60" maxlength="60" required="required" js-name="Name" />
</label>
<br />
<label>Email:
<input name="Email:" type="email" value="" size="60" required="required" js-name="Email" />
</label>
<br />
<label>Phone:
<input name="Phone" type="text" size="60" required="required" js-name="Phone" />
</label>
<br />
<label>Country:
<input name="Country" type="text" size="60" required="required" js-name="Country" />
</label>
<br />
<input name="Submit" type="submit" id="submit" value="Submit" />
</form>
Comments
Check this simple jQuery plugin
Comments
valijate plugin might help you. it uses 'data-xxxx' attributes for the validations. here is form validation guide.