JAB
JAB

Reputation: 3616

Jquery validation of input array elements manually

<input type="text" name="member_name[]" size="13" value="">  
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">

How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?

Upvotes: 0

Views: 3132

Answers (5)

thecodeparadox
thecodeparadox

Reputation: 87073

$('input:submit').click(function() {
    $('form').submit(function(e) {
        $("input:text[name^='member_name']").each(function() {
            if (!$.trim($(this).val()).length) {
                alert('Name Field should not leave empty');
                return false; // or e.preventDefault();
            }
        });
    });
});

Upvotes: 2

Eric
Eric

Reputation: 97571

var invalidInputs = $('input').filter(function() {
    return $(this).val() == "";
});

var valid = invalidInputs.length == 0

Upvotes: 1

Iladarsda
Iladarsda

Reputation: 10696

Not most advance, but simple & clear method.

 $("form").submit(function(event) {

    var inputLength = $('input[type="text"]').val().length;  // check for value length

    if ($('input').val().length > 0) {
        // submit if input value is length > 0 
        alert('Form submitted.');
    }
    else {
        // error if input value is NOT length > 0 
        alert('Fill the form.');
        event.preventDefault();
    }
});

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:

$("form").submit(function(event) {
    if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
        window.alert("No member name should be empty.");
        event.preventDefault();
    }
});

EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:

$("form").submit(function(event) {
    if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
            return $.trim(this.value) == "";
        }).length) {
        window.alert("No member name should be empty.");
        event.preventDefault();
    }
});

Upvotes: 3

Dogbert
Dogbert

Reputation: 222128

var valid = true;
$('input').each(function(){
  if($(this).val() == "") {
     valid = false;
  }
});

// use valid here

Upvotes: 1

Related Questions