Simple Form validation jQuery snippet

Simple-Form-validation-jQuery-snippet

Here is the showing of a basic form that we will be validated using the jQuery validate code.

Add this script to your HTML page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

HTML Form Code

<form id="basic-form" action="" method="post">
	<p>
		<label for="name">Name <span>(required, at least 3 characters)</span></label>
		<input id="name" name="name" minlength="3" type="text" required>
	</p>
	<p>
		<label for="email">E-Mail <span>(required)</span></label>
		<input id="email" type="email" name="email" required>
	</p>
	<p>
		<input class="submit" type="submit" value="SUBMIT">
	</p>
</form>

jQuery Code

<script type="text/javascript">
$(document).ready( function(){//simple validation at client's end
  $( "#IntelligentForm" ).submit(function( event ){ //on form submit   
    var proceed = true;
    //loop through each field and we simply change border color to red for invalid fields       
   $("#IntelligentForm input[required=true], #IntelligentForm select[required=true]").each(function(){
	    $(this).css('border-color',''); 
	    if(!$.trim($(this).val())){ //if this field is empty 
	    $(this).css('border-color','red'); //change border color to red   
	    proceed = false; //set do not proceed flag
	}
        });
	if(proceed){ //if form is valid submit form
		return true;
	}
	event.preventDefault();	
   });
    //reset previously set border colors and hide all message on .keyup()
    $("#IntelligentForm input[required=true], #IntelligentForm select[required=true]").keyup(function() { 
		$(this).css('border-color',''); 
		$("#result").slideUp();
   });
});

</script>

The output of the above example will look something like this:

We Well organized and easy-to-understand Interactive tutorials With lots of examples of how to use Tutorials WordPress, PHP, Bootstrap, Bootstrap 4, HTML, CSS, AJAX, jQuery, Woocommerce, Post, Database, Javascript, Theme, Responsive, Templates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact us

Fill in the form below or give us a call and we'll contact you. We endeavour to answer all enquiries within 24 hours on business days.