all input field validation through single/minimum line on code with jQuery
I have a form in which I have 30 input boxes and 10 text areas and 3 select boxes (updated) field and all are mandatory fields.
How do I apply validation through jQuery /javascript together for all input fields that it can't be blank/empty/NULL.
I don't want to use each time each input box's ID and create a separate validation for each input box and text area.开发者_StackOverflow中文版
If any input field is blank then it's border become red and when a use going to write something then become normal( no border i.e. remove that class)
UPDATE:
There are also select boxes ..how do I validate them together?
Something like this:
$("#myForm").submit(function() {
// if there are some empty inputs
if($(":input[value]").length != $(":input").length)) {
// filter out the empty ones, apply some CSS
$(":input").filter(function() {
return this.value.length == 0;
}).addClass("blank");
// do not submit
return false;
}
});
$(":input").blur(function() {
if(this.value.length > 0) {
$(this).removeClass("blank");
}
});
- Remove the red border from each text, textarea, and list box field.
- Filter out elements that contain at least 1 non-whitespace character - \S+
- Add a red border to the remaining elements
javascript
function validate() {
return $("input:text,textarea,select").removeClass('blank').filter(function() {
return !/\S+/.test($(this).val());
}).addClass('blank').size() == 0;
}
$('#form').submit(validate);
css
.blank {
border: 1px red solid;
}
精彩评论