开发者

all input field validation through single/minimum line on code with jQuery

开发者 https://www.devze.com 2022-12-22 15:03 出处:网络
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.

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");
    }
});


  1. Remove the red border from each text, textarea, and list box field.
  2. Filter out elements that contain at least 1 non-whitespace character - \S+
  3. 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消