Behseini
Behseini

Reputation: 6330

Issue With Contact Form Validation

I am trying to validate a simpla contact form using HTML5 Patterns and jQuery as below:

<form action="test.php" method="post" id="myForm">
  <input type="text" name="name"   id="name"   class="form-control"  pattern="[A-Za-z ]+" autofocus placeholder=" Please Enter Your Name" >
  <input type="tel"  name="phone"  id="phone"  class="form-control"  pattern="\d{3}[\-]\d{3}[\-]\d{4}" autofocus  placeholder="xxx-xxx-xxxx"  >

  <button type="submit" name="submit">Send Email</button>
</form>

and here is the jquery code I am using to validate the field if they are empty:

$(document).ready(function () {
        $('#myform').submit(function () {
            var abort = false;
            $("div.alert").remove();
            $('input[type="text"]').each(function () {
                if ($(this).val() === '') {
                    $(this).after('<div class="err"><p>Phone Field Cant be Empty</p></div>');
                    abort = true;
                }
            }); // go through each required value
            if (abort) {
                return false;
            } else {
                return true;
            }
        }) //on submit
}); // ready

but for what ever reason it is not validating the form! Can you please let me know what I am doing wrong here?

Upvotes: 4

Views: 190

Answers (2)

Richard de Wit
Richard de Wit

Reputation: 7452

There isn't ANY need for JS/jQuery whatsoever. Everything can be validated with HTML5.

Use required in the input field to make sure the values are not empty and use pattern to check contents (like you already did).

<input ... required>

HTML

<?php 
    /* The form is POSTed to the same page to check the sumitted values */
    print_r($_POST); 
?>

<form action="" method="post" id="myForm">
    <input type="text" name="name" id="name" class="form-control" pattern="[A-Za-z ]+" autofocus placeholder="Please Enter Your Name" required>
    <input type="tel" name="phone" id="phone" class="form-control" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="xxx-xxx-xxxx" required>
    <button type="submit" id="send">Send Email</button>
</form>

Also best practice is to use on, as in $("#element").on("click", function(){, instead of .click(function(){ or .submit(function(){.

Upvotes: 2

Jared
Jared

Reputation: 3016

if ($(this).val() == '') {
    $('<div class="alert"><p>Phone Field Cant be Empty</p></div>').insertAfter($(this));

    abort = true;
}

I gave the new div class alert because you were removing the wrong element before validating.

I modified the logic to check if the value is equal to false, not equal to an empty string, in case the value property isn't even set (you can never be too careful).

You were also using after() which gets the next sibling of an element and doesn't insert any content.

Full code:

$(document).ready(function () {
        $('#myform').submit(function () {
            var valid = true;

            $("div.alert").remove();

            $(this).find('input').each(function () {
                if ($(this).val() == '') {
                    $('<div class="alert"><p>Phone Field Cant be Empty</p></div>').insertAfter($(this));

                    valid = false;
                }
            });

            if (valid) {
                return true;
            } else {
                return false;
            }
        });
});

You'll notice I made slight changes:

I renamed abort to valid, because it's a good idea to try and evaluate for the positive thing first. It's a more explanative name too: why are we aborting? Because it's not valid (valid = false;).

Instead of validating ALL inputs, I selected inputs that are found within the form using find(). Just in case there's more than one form on the page.

Upvotes: 0

Related Questions