views:

340

answers:

2

i have a form in which have 30 input box and 10 text area field and all are mandatory fields. How do i apply a validation through jQuery / javascript together for all input field 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

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

+3  A: 

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");
    }
});
karim79
working fine but there is two syntax error 1. remove extra `)` after .length function 2.add `(` after `solid;` this shoud be css("border","1px red solid";`)`
diEcho
Thank You Karim.
diEcho
Still helping... Thanks
Garis Suero
+1  A: 
  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;
}
Anurag
it validate but page go on action page , it does not stop at that page and that error css e disply only for few seconds
diEcho
and in css there should be `border` instead of `blank`
diEcho
it was submitting the form because i just posted a snippet. the `onsubmit` handler function must return false or stop the event to prevent the form from submitting. thanks for pointing out the css fix.
Anurag
now it works fine, but it does not work on select box. and one more things i want when user going to write something then css should be remove.
diEcho
i fixed that using second set of code of first answer given by Karim.but select box still unvalidated?
diEcho
i had problems with select boxes too. apparently the browser (or jquery) is automatically selecting the first item. So I tried putting a junk item as the first option whose value was blank as it fits nicely with our textfields and textareas . `<option value="">Please Select...</option>`
Anurag