Forms are one of the strongest reasons that have built the web as helpful as it is today, and for this cause, it’s still included in the HTML5 specifications. Since, after the release of HTML5 and Jquery, that provides an efficient way to handle forms before hitting the submit button. It has become much easier for the designers to supply a valid form information through front-end. The Jquery validation form makes it easier for the user as well as you to handle the common forms very gracefully.

 

What’s a Jquery validation form?

The Jquery is a JS plugin, that lets to do a task in just a few lines, which could take hundreds of lines in Javascript. A validated form makes sure any information you send through forms is valid, whether it is a Name, email address or any other form stuff. A Jquery validated form is a validation of forms using Jquery, as simple as it sounds.

 

Jquery form validation - how to create form validation through Jquery

The form validation shows the errors if any in the forms before submitting the form to the back-end.

 

Plugins and Resources

Since we are creating a form validation through Jquery, the first and the most important plugin we need is Jquery plugin. You can directly link the Jquery file through this link.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

 

If you want to make your form a bit more helpful, you can add images besides the input fields. I have added an exclamation mark if there are any errors and a green tick to the right while the input values are valid. You can use the images from an open source project, Font-Awesome. Here’s a direct link if you couldn’t find a hint to their document page.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

 

The HTML content

Here’s the HTML form skeleton that we are going to work on.  For the purpose, we don’t need too many elements. Name, email and a password would  be enough to work on, and these are the widely used input fields as well. We have omitted the basic head snippets and marked a tag directly below the “body” tag. The Jquery plugin and font-awesome icons links come under this head.

 

The HTML content goes like this

<form class="fb" action="">
   <p>A Jquery Validation form</p>
   <div><i class="fa fa-exclamation-circle fn"></i>
        <input type="text" name="name" id="name" placeholder="NAME">
        <i class="fa fa-check pn"></i>
   </div>
   <div><i class="fa fa-exclamation-circle fe"></i>
        <input type="email" name="email" placeholder="EMAIL" id="email">
        <i class="fa fa-check pe"></i>
   </div>
   <div><i class="fa fa-exclamation-circle fp"></i>
        <input type="password" name="password" id="pass" placeholder="PASSWORD">
        <i class="fa fa-check pp"></i>
   </div>   
   <div></i><input id="sub" type="submit" value="submit"></i></div>
</form>

 

As I have told you, the basic input elements would be fine. The above code is pretty well self-explanatory, except the <i> tag and it’s unique class name, “fa fa-whatever”. The <i> tag is the component of the font-awesome library. To add the font-awesome icons, we need a <i> tag with a class name that points out which image to link. If you have noticed the code, the class = “fa fa-exclamation-circle” and class= “fa fa-check” links to the exclamation image and the check images. If you want a full list of all the font-awesome icons, you can refer the Font-Awesome cheatsheet. Also, note that I haven’t given the form any action, as we are just dealing with the front end.

 

Styling the form fields

Here comes my favorite part, styling the form fields, but for today, we will finish this up with just a few touches. The above code is just the styling of different elements. Here I have styled the “submit” button differently to distinguish it from other inputs, of course. I have also rounded the corners and enabled a bottom border as the input field gets the focus.

.fb{ 
   display: block; 
   text-align: center; 
}
p {
   font-family: Calibri;
   margin-bottom: 50px;
   font-size: 24px;
   font-weight: 400;
   margin-bottom: 40px;
}
input {
   text-align: center;
   padding: 15px;
   background: #efefef;
   border: none;
   width: 300px;
   font-size: 14px;
   margin: 5px 10px 0px; 
   text-transform: none;
   border-radius: 15px;
   border-bottom: 1px solid transparent;
}
input:focus {
   outline: none;
   border-bottom: 1px solid #66aa66;
}
#sub {
   padding: 10px;
   background: #cc3333;
   width: 200px;
   font-family: calibri;
   text-transform: uppercase;
   margin-top: 50px;
   font-weight: 500;
   letter-spacing: 0px;
   font-size: 18px;
   color: #fff;
}
#sub:hover {
   cursor: pointer;
}

 

Because most of the users would be reading this from their smartphone, it’s better to make the final form design responsive, so you don’t have to scroll left to right, to type in your input.

Read also, why does responsive website design matters.

 

The media query for the screens up to width 420px shuts off the icons to avoid crowdedness. The other media query for minimum width 421px does not disable the icons. Also, here the width of inputs have been reduced to 75% so that air remains between the elements. The final media query, for screens with a minimum width of 1300px, slightly styles the form body.

@media(max-width: 420px) {
   input {
      width: 80%;
   }
   .fa {
      display: none !important;
   }
}
@media(min-width: 421px) {
   input {
      width: 75%;
   }
}
@media(min-width: 1300px) {
   form {
      margin: 5px 450px 10px;
      padding: 10px;
      padding-bottom: 80px;
      border: 1px solid #e3e3e3;
      background: #fbfbfb;
   }
}

 

That’s all with the CSS.

 

The Programming stuff

When you write your JS code in Jquery, it feels like you are writing articles. It makes the entire process less typing and more thinking. Well, let’s not talk about the Jquery here, some other article maybe. Another thing to consider in programming is the logic of the program. The code below may look odd to some designers, but it works flawlessly. See also, DOM tips to reduce code size.

 

Let us begin coding the logic. First of all, we will change the color of the icons to transparent as soon as the Javascript loads, so they won’t be initially visible. Some may prefer using the .hide( ) Jquery function. The hide function disappears the icons, but when you turn them on, the input field shifts to the right. To avoid the floating, it’s better to change their visibility.

$('.fa').css('color','transparent');

 

Now we will define the actions. We add two events to name input using .on( ) function, the change, and the blur. Whenever the user changes or leaves the input field, these events will be triggered.

$('#name').on("change blur" ,function() {
   //Function definition comes here
});

 

Under this event, firstly, we would extract the data from the input field using the .val( ) function.

var n = $('#name').val();

 

We need to define functions to check whether the data entered is correct or not. So we define a function named validateName( ) outside this events, so it is globally accessible. The function validateName( ), takes in an argument which contains the name string. This value of n has been extracted from the name input field using the .val( ) function. Inside this function, a variable nr holds the regular expression string, which specifies the name format. If the name string matches the regular expression string, using expr.test(n), it returns true. Same goes with the validateEmail( ) function which checks the format of email string.

function validateName(n) {
    var nr = /.[a-zA-Z]+$/;
    return nr.test(n);
};
function validateEmail(em) { 
   var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 
   return expr.test(em);
};

 

Coming back to $(‘#name’).on(“change blur”, function( ), after the first line, we will check if the name string matches with the specified format or not. For this, we add an if statement with the negative condition first, that is if the input doesn’t match the string or the length of the string is zero, we would signal the user by showing a red alert. The $(‘.pn’) changes the color of the tick icon to transparent since we don’t want to show the tick if the input entered is wrong. Whereas, $(‘.fn’) shows the alert icon in red color.

if( !validateName(n) || n.length==0 ) {
      $('.pn').css('color','transparent');
      $('.fn').css('color','#c44');
      $('#name').css('border','1px solid red');
   }

 

The else statement would do the inverse by making the tick visible and hiding the alert.

else {
      $('.pn').css('color','#2c2');
      $('.fn').css('color','transparent');
      $('#name').css('border','1px solid transparent');
   }

 

So the final function for the Name input becomes,

$('#name').on("change blur" ,function() {
   var n = $('#name').val();
   if( !validateName(n) || n.length==0 ) {
      $('.pn').css('color','transparent');
      $('.fn').css('color','#c44');
      $('#name').css('border','1px solid red');
   }
   else {
      $('.pn').css('color','#2c2');
      $('.fn').css('color','transparent');
      $('#name').css('border','1px solid transparent');
   }
});

 

The email input has the similar code. Here the function would check the format through the validateEmail( ) function. The final code for email is,

$('#email').on("change blur" ,function() {
   var em = $('#email').val();
   if( !validateEmail(em) || em.length==0 ) {
      $('.pe').css('color','transparent');
      $('.fe').css('color','#c44');
      $('#email').css('border','1px solid red');
   }
   else {
      $('.pe').css('color','#00cc00');
      $('.fe').css('color','transparent');
      $('#email').css('border','1px solid transparent');
   }
});

 

The password input can accept all the characters. So here we can’t apply any format constraint. But we can check whether the password is long enough? So inside the if statement, we would check if the length of the password is greater than 6 and less than 12. The code for the same is,

if( pa.length<=6 || pa.length>=12 ) {
//Function definition
}

 

Therefore, the final code for validating the password is,

$('#pass').on("change blur" ,function() {
   var pa = $('#pass').val();
   if( pa.length<=6 || pa.lenght>=12 ) {
      $('.pp').css('color','transparent');
      $('.fp').css('color','#c44');
      $('#pass').css('border','1px solid red');
   }
   else {
      $('.pp').css('color','#00cc00');
      $('.fp').css('color','transparent');
      $('#pass').css('border','1px solid transparent');
   }
});

 

 

Now before submitting the data, we can alert the user about the errors using the following code.

$('#sub').click(function(evt) {
   var n = $('#name').val();
   var em = $('#email').val();
   var pa = $('#pass').val();
   if(!validateName(n) || n.length==0 || !validateEmail(em) || 
       em.length==0 || pa.length<=6 || pa.length>=12) {
           alert("Error!");
           evt.preventDefault();
   }
   else {
     alert("Form submitted successfully");
   }
});

 

The final code for our form validation is,

//Initial Image Visibility
$('.fa').css('color','transparent');

//Validate Functions
function validateEmail(em) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return expr.test(em);
};
function validateName(n) {
    var nr = /.[a-zA-Z]+$/;
    return nr.test(n);
};

//Actions
$('#name').on("change blur" ,function() {
   var n = $('#name').val();
   if( !validateName(n) || n.length==0 ) {
      $('.pn').css('color','transparent');
      $('.fn').css('color','#c44');
      $('#name').css('border','1px solid red');
   }
   else {
      $('.pn').css('color','#2c2');
      $('.fn').css('color','transparent');
      $('#name').css('border','1px solid transparent');
   }
});

$('#email').on("change blur" ,function() {
   var em = $('#email').val();
   if( !validateEmail(em) || em.length==0 ) {
      $('.pe').css('color','transparent');
      $('.fe').css('color','#c44');
      $('#email').css('border','1px solid red');
   }
   else {
      $('.pe').css('color','#00cc00');
      $('.fe').css('color','transparent');
      $('#email').css('border','1px solid transparent');
   }
});

$('#pass').on("change blur" ,function() {
   var pa = $('#pass').val();
   if( pa.length<=6 || pa.lenght>=12 ) {
      $('.pp').css('color','transparent');
      $('.fp').css('color','#c44');
      $('#pass').css('border','1px solid red');
   }
   else {
      $('.pp').css('color','#00cc00');
      $('.fp').css('color','transparent');
      $('#pass').css('border','1px solid transparent');
   }
});

$('#sub').click(function(evt) {
   var n = $('#name').val();
   var em = $('#email').val();
   var pa = $('#pass').val();
   if(!validateName(n) || n.length==0 || !validateEmail(em) || 
       em.length==0 || pa.length<=6 || pa.length>=12) {
          alert("Error!");
          evt.preventDefault();
   }
   else {
     alert("Form submitted successfully");
   }
});

 

If you have done everything perfectly, the final output would be like this,

 

[codepen_embed height=”393″ theme_id=”21620″ slug_hash=”zrWaQv” default_tab=”result” user=”devstreak”]See the Pen <a href=’http://codepen.io/devstreak/pen/zrWaQv/’>Jquery validation form</a> by Devstreak (<a href=’http://codepen.io/devstreak’>@devstreak</a>) on <a href=’http://codepen.io’>CodePen</a>.[/codepen_embed]

 

Conclusion

Forms are used on almost every website. Even on this site, you need to pass through a signup form before commenting. So to make sure the back end gets a valid data, you can validate the data. Although the inbuilt browser functions do not let you submit the forms with invalid data, but still they are not better than custom validation. And with Jquery, the whole process becomes painless. With the growing internet users, the data is increasing and most of the data submitted through forms. It’s better to apply the validation and save everyone’s time.

 

How are you validating your forms? Share your comments and thoughts.

Share on Facebook Tweet on Twitter Post on Google+ Buffer