Julian
Julian

Reputation: 23

Submit Form Validation

I'm trying to check whether if a input[required] has a value, if not then don't submit the form and throw back errors and if all are filled in the submit the form. I believe it's an issue with my return false not being in the correct place.

JavaScript:

$('#MyForm').bind('submit', function() {

   $('#MyForm input[required]').each(function() {
       var hasValue = $(this).val().length;
       var hasRequired = $(this).prop('required');
       var inputClass = '#error-' + $(this).attr('name');

        function validator() {
           if( hasValue == 0 ) {
                console.log('Step 1');
                $(inputClass).show();
                $(this).addClass('error')
            } else {
                console.log('Step 2');
                $(inputClass).hide();
                $(this).removeClass('error')
            }
        }
        if( validator() == true ) {
           console.log('Form Submitted');
        //   $('#myForm').submit();
       }
   });

   return false;
});

Example HTML:

<form class="contact-form" id="MyForm" role="form" method="POST" action="" novalidate="novalidate">
                <div class="group">
                    <label for="first_name">First Name *</label>
                    <input type="text" id="first_name" name="first_name" placeholder="First Name" required="" aria-required="true">
                </div>
                <div class="group">
                    <label for="last_name">Last Name *</label>
                    <input type="text" id="last_name" name="last_name" placeholder="Surname" required="" aria-required="true">
                </div>
                <input id="submit" name="submit" type="submit" value="Send" class="btn">
            </form>

Upvotes: 2

Views: 289

Answers (5)

Ruhul Amin
Ruhul Amin

Reputation: 1779

You can make it in more organised way, add more rules for other form fields( like, emails, phone etc. ) if you want. I also added error class to the parent so that you can style it in your own way.

jQuery(document).ready(function($) {

     $('#MyForm').on('submit', function(){
        var form = this;
        if(validateForm(form)) {
            // Validation pass.  you can process your form
            alert('Form validated');
        }
        else{
            event.preventDefault();
            return false;
        }
      });

        function validateForm(form) {
            valid = true;

            $(form).find('input[type=text], input[type=email]').each(function(i, val){
                if(validateField(val, true) == false) { valid = false; }
            });

            return valid;
        }
        function validateField(field, submit) {
            var val = $(field).val();
            if($(field).attr('aria-required') == 'true' && submit){
                if(val == '') {
                    $(field).parent().removeClass('valid');
                    $(field).parent().addClass('error');
                    return false;
                }else {
                    $(field).parent().removeClass('error');
                    $(field).parent().addClass('valid');
                    return true;
                }
                // you can more specific
                if($(field).attr('type') == 'text') {
                    $(field).parent().addClass('error');
                    return false; }
                else {
                    $(field).parent().removeClass('error');
                    $(field).parent().addClass('valid');
                    return true;
                }
            }
        }

    });

JSfiddle link: https://jsfiddle.net/afsgp2bj/2/

Upvotes: 1

VJI
VJI

Reputation: 81

Use required="" in input field and it will work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="testForm" id="testForm">
<input name="test" id='test' required="required"/>
<button type="submit">submit </button>
</form>

  

Upvotes: 0

You can also try button click event and event.preventDefault():

event.preventDefault() will prevent parent event to call

$("#submit").click(function (event) {
    $('#MyForm input[required]').each(function () {
        var hasValue = $(this).val().length;
        var hasRequired = $(this).prop('required');
        var inputClass = '#error-' + $(this).attr('name');

        function validator() {
            if (hasValue == 0) {
                console.log('Step 1');
                $(inputClass).show();
                $(this).addClass('error');
                event.preventDefault();
                return false;
            } else {
                console.log('Step 2');
                $(inputClass).hide();
                $(this).removeClass('error');
            }
        }
        if (validator() == true) {
            console.log('Form Submitted');
            //$('#myForm').submit();
        }
    });

});

Upvotes: 0

Dr.Flink
Dr.Flink

Reputation: 572

You should remove your function inside your loop:

$(function() {
    $('#MyForm').bind('submit', function() {
        $('#MyForm input[required]').each(function() {
            var hasValue = $(this).val().length;
            var hasRequired = $(this).prop('required');
            var inputClass = '#error-' + $(this).attr('name');

            if( hasValue == 0 ) {
                console.log('Step 1');
                $(inputClass).show();
                $(this).addClass('error')
            } else {
                console.log('Step 2');
                $(inputClass).hide();
                $(this).removeClass('error')
            }
        });

        return false;
    });
});
.error {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="contact-form" id="MyForm" role="form" method="POST" action="" novalidate="novalidate">
                <div class="group">
                    <label for="first_name">First Name *</label>
                    <input type="text" id="first_name" name="first_name" placeholder="First Name" required="" aria-required="true">
                </div>
                <div class="group">
                    <label for="last_name">Last Name *</label>
                    <input type="text" id="last_name" name="last_name" placeholder="Surname" required="" aria-required="true">
                </div>
                <input id="submit" name="submit" type="submit" value="Send" class="btn">
</form>

Upvotes: 0

kernal_lora
kernal_lora

Reputation: 1155

I hope this solution works for you. You placed return statement inside your loop. You need to place the return statement inside validation function.

function validator(hasValue,inputClass) {
           if( hasValue == 0 ) {
                console.log('Step 1');
                $(inputClass).show();
                $(this).addClass('error');
                return false;
            } else {
                console.log('Step 2');
                $(inputClass).hide();
                $(this).removeClass('error');
                return true;
            }
        }



$('#MyForm').bind('submit', function() {

   $('#MyForm input[required]').each(function() {
       var hasValue = $(this).val().length;
       var hasRequired = $(this).prop('required');// I don't know what it does for you.
       var inputClass = '#error-' + $(this).attr('name');
        if( validator(hasValue,inputClass) ) {
           console.log('Form Submitted');
        //   $('#myForm').submit();
       }
   });

Inside for loop you placed function which is not good.

Upvotes: 1

Related Questions