0
<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.?

2
  • 2
    Validate what? Are those required fields? E-mail addresses? Please clarify your question. Commented Aug 8, 2011 at 10:02
  • updated question.. please check Commented Aug 8, 2011 at 10:04

5 Answers 5

3

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();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

2
$('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();
            }
        });
    });
});

Comments

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

// use valid here

Comments

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

var valid = invalidInputs.length == 0

2 Comments

@naveen: You're not really supposed to change someone's answer like that! Not that I mind, but it's not the done thing!
i am sorry if i have offended you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.