Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Creating your own Form Validation Plugin with JavaScript

In this article we will learn how you can guide your users to fulfill a form; you can use this concept to create your own form validation plugin with Javascript.

Some of us have used a plugin to validate their form before submitting it. But it seems like that we don’t know enough how the field validation works. That’s why I’ve decided to talk about form validation today. Willing to show the way it works and if you go further, you can create your own form validation plugin, using regular expressions to test the user inputs.

Here is the picture of our article:

img1

Explanation:
  • While the user is entering the text, we show him explanation text in green;
  • We also test if his input is correct, if not, we show an error message in red;
  • We also use regular expressions to test if the typed value matches a given pattern

Html Code. Put this in FormValidationJS.htm file

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form validation!!!</title>
<linkhref="formValidationJS.css"rel="stylesheet"type="text/css"/>
<scriptsrc="jquery.1.7.2.js"type="text/javascript"></script>
<scriptsrc="formValidationJS.js"type="text/javascript"></script>
</head>
<body><p> </p>
<center>
<formaction=''id='newUserForm'method="post"enctype="multipart/form-data">
<divclass='field'> Your Full Name<br/>
<inputid="fullname"name="fullnameVar"type="text"class="input"/><br/>
<divclass='report'>
<labelid="fullname_info"class='info'>type your name(s) four words or less</label><br/>
<labelid="fullname_error_message"class='error'>Your name must be alpha-numeric and not null. Please check and correct this value</label>
</div>
</div>

<divclass='field'>Your email<br/>
<inputid="email"name="emailVar"type="text"class="input"/>
<divclass='report'>
<labelid="email_info"class='info'>will help us to contact you back!<br/></label>
<labelid="email_error_message"class='error'>Ooops! this email is not valid</label>
</div>
</div>

<divclass='field'>Choose a password<br/>
<inputid="password"name="passwordVar"type="password"class="input"/>
<divclass='report'>
<labelid="Label3"class='info'>your secret word <br/></label>
<labelid="Label4"class='error'>This password is not enough strong! combine with a number please</label>
</div>
</div>


<divclass='field'>Retype your password<br/>
<inputid="password2"name="passwordVar2"type="password"class="input"/>
<divclass='report'>
<labelid="password2_info"class='info'>we want to check if you'll surely never forget this password<br/></label>
<labelid="password2_error_message"class='error'>Oops! How come you forgot your pass only now? The two passwords must match. please check again</label>
</div></div>


<divclass='field'>A picture of you :)<br/>
<inputid="picture"name="pictureVar"type="file"class="input"/>
<divclass='report'>
<labelid="picture_info"class='info'>Want to see your pic<br/></label>
<labelid="picture_error_message"class='error'>This field is required</label>
</div></div>

<divclass='field'>Your birth date<br/>
    mm   /   dd   /   yyyy<br/>
<inputid="month"name="monthVar"type="text"class="input_40"/> 
<inputid="day"name="dayVar"type="text"class="input_40"/> 
<inputid="year"name="yearVar"type="text"class="input_40"/> 
<divclass="report">
<labelid="birthdate_info"class='info'>Share your birthday and age with us please<br/></label>
<labelid="birthdate_error_message"class='error'>Ooops! This date is not valid. Please correct it</label>
</div></div>

<p>
<inputtype="submit"value="Register Now"/>
</p>
</form></center>
</body>
</html>

Look inside the head tag:

<linkhref="formValidationJS.css"rel="stylesheet"type="text/css"/>
<scriptsrc="jquery.1.7.2.js"type="text/javascript"></script>
<scriptsrc="formValidationJS.js"type="text/javascript"></script>
 

You will need three more files:

  • A cascading style sheet named formValidationJS.css to design (or beautify) your html page with colors and so on.
  • jquery.1.7.2.js The jQuery library: downloadable on jQuery website. I’m using the 1.7.2 version, which is the last released;
  • And the validation code file, written in JavaScript-and-jQuery. The name of this file is formValidationJS.js

Here is the cascading style sheet:

*{margin:0auto; padding:0auto; font-family:Arial}
.left{float:left}
.right{float:right}
.clear{clear:both}
.error{color:Red; display:none; font-family:Verdana; font-size:80%;}
.report{min-height:20px;}
.info{color:#383;display:none;font-family:Verdana; font-size:80%;}
.none{border:none; background:none; list-style:none}
input[type='text'],input[type='password']{border:1pxsolid#ccc; height:20px;width:220px; background:#efefef; color:#363;}
input[type='file']{border:none; line-height:26px;width:220px; background:#efefef; color:#363;}
input[type='submit']{border:1pxsolid#fff;background:#3366a9;color:White;padding:3px10px;}
input.input_40{width:40px;}
.borderable_box{border:1pxsolid#ccc;}
input.gray_bg{background:#efefef}
input.red_bg{background-color:#fcc}

Nothing to explain here, we only want to color our input field and their error messages…

Validation Code File

Onfocus()

Each time a field receives the focus, we want to show instructions that are inside the .info element and that was hidden via CSS. Here is how to do it.

//-----On focus, show info
    $('div.field').each(function () {
var _block = $(this);
        _block.find('input').focus(function () {
var _input = $(this);
            _block.find('.info').fadeIn(300);
        }).focusout(function () {
            _block.find('.info').fadeOut(100);
});
    });

Validating the name

A name can’t contain a number, a special char or a symbol. In addition, the full name must be at list 3 characters long! We also allow names consisting of one to four words. A name like ‘Xian Chin XiaoJu’ is allowed, the same than ‘Mark Zuckerberg’ or ‘Ricardhino’. But you can’t type a long name like: ‘Foo Bar Gentle Richard Sergio’ thereis five words and this will not be validated. A friend of mine used to cut his name ‘ASENGO JEI’ in ‘As’, this will not work because the word‘As’ has less than three letters.

Here is the code to validate the name:

//------------validate name
varfullNameObject = formObject.find('#fullname');
fullNameObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
meError |= (myValue.split(' ') != null) ? myValue.split(' ').length > 4 : false; //more than 4 words ?
var pattern = /^([a-zA-ZÀ-ÿ\s]{3,})$/;
varexpr = newRegExp(pattern);
meError |= !(expr.exec(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
}
errorOccured = meError;
    });
//-----------end

There is a regular expression!!! Let me explain it:

var pattern = /^([a-zA-ZÀ-ÿ\s]{3,})$/;
varexpr = newRegExp(pattern);
meError |= !(expr.exec(myValue));
  • ^ means that a name must begin and
  • ($) means that it must end with a set of chars in parentheses,
  • [a-zA-ZÀ-ÿ\s]{Alphabetical letters, from a toz including lower and uppercase. Some European name such as Portuguese, French,
  • Spanish names have accents over vowels. That’s why I added the area from À to ÿ. Finally, I allow the space char in a name with \s

The code:

meError |= myValue == null

Is the same as:

meError = meErro|(myValue == null)

Validating the email

//------------validate email
varemailObject = formObject.find('#email');
emailObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
varexpr = newRegExp(pattern);
meError |= !(expr.test(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
}
errorOccured = meError;
    });
//-----------end
 
Note the email pattern
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

This mean that the input must start with one or more alphanumeric char including stop, _ , - , lower and upper case; contain a @ followed by one or more alphanumeric char including stop, - , lower and upper case; also contain a point followed by two to four letters.

Validating passwords

I’d like to warn a little about password validation, have a look at this code and I will comment afte.r

//------------validate passwords
varpasswordObject = formObject.find('#password');
passwordObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
var pattern = /^.{6,}/;
varexpr = newRegExp(pattern);
meError |= !(expr.test(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });

var password2Object = formObject.find('#password2');
password2Object.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = me.val() != passwordObject.val();
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
}
errorOccured = meError;
    });
//-----------end

 

Pay attention!!! Don’t store a password to use it after! It doesn’t work

So, if a variable named me is referencing a password input you are not allowed to write this:

varmyValue = me.val();// Never Never and Never
alert(myValue); //myValue is nothing !!!

Write this instead:

alert(me.val()); //the pass wordwill be shown in a dialog

For security sake and according to the JavaScriptstandard of w3c (if no mistake on my behalf) YOU CAN’T STORE A PASSWORD IN A VARIABLE!!!

Validating days, months and years

Let’s say something about days, months and years validation. A day consists in one or two numbers, a day is between 0 and 32 stating from (1 to 31). The month is validated the same way as the day, except that it starts from 1 to 12. For the field of years, I don’t allow people that are more than 100 years old. See the code:

//------------validate day
vardayObject = formObject.find('#day');
dayObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
meError |= myValue< 1;
meError |= myValue> 31;

var pattern = /^\d{1,2}$/;
varexpr = newRegExp(pattern);

meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;

    });
//-----------end

//------------validate month
varmonthObject = formObject.find('#month');
monthObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
meError |= myValue< 1;
meError |= myValue> 12;

var pattern = /^\d{1,2}$/;
varexpr = newRegExp(pattern);

meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end
//------------validate year
varyearObject = formObject.find('#year');
yearObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
varthisYear = new Date().getYear() + 1900; ;
var pattern = /^\d{4}$/;
varexpr = newRegExp(pattern);

expr = newRegExp(pattern);
meError |= myValue<thisYear - 100;
meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end

Submitting the form

In the jQuery submit () event, you can cancel the sending of a form to the server by returning false. In my code I have stored errors state in a variable named errorOccured. So, I need to return true if errorOccured is false, and return false if the errorOccured variable is true. See how I do it:

//-----submit form----
//the user has clicked on the submit button, or pressed ENTER
formObject.submit(function () {
formObject.find('input').each(function () {
if ($(this).val() == '' || typeof $(this).val() == undefined || $(this).val() == null) {
errorOccured = true;
errorMessage += "<br/>All fields are required";
            }
        });
return !errorOccured;
    });
//-------END

The full source code: formValidationJS.js

/// <reference path="jquery.1.7.2.js" />

$(document).ready(function () {
varformObject = $('#newUserForm');
varerrorOccured = false;
varerrorMessage = "We could not submit your form. Please check the invalid field and correct it";

//-----On focus, show info
    $('div.field').each(function () {
var _block = $(this);
        _block.find('input').focus(function () {
var _input = $(this);
            _block.find('.info').fadeIn(300);
        }).focusout(function () {
            _block.find('.info').fadeOut(100);
        });
    });
//-----ENd---



//------------validate name
varfullNameObject = formObject.find('#fullname');
fullNameObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
meError |= (myValue.split(' ') != null) ? myValue.split(' ').length > 4 : false; //...
var pattern = /^([a-zA-ZÀ-ÿ\s]{3,})$/;
varexpr = newRegExp(pattern);
meError |= !(expr.exec(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end



//------------validate email
varemailObject = formObject.find('#email');
emailObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
varexpr = newRegExp(pattern);
meError |= !(expr.test(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end


//------------validate passwords
varpasswordObject = formObject.find('#password');
passwordObject.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = false;
meError |= myValue == null || typeofmyValue == undefined;
var pattern = /^.{6,}/;
varexpr = newRegExp(pattern);
meError |= !(expr.test(myValue));
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });

var password2Object = formObject.find('#password2');
password2Object.keyup(function () {
var me = $(this);
varmyValue = me.val();
varmeError = me.val() != passwordObject.val();
if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end



//------------validate day
vardayObject = formObject.find('#day');
dayObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
meError |= myValue< 1;
meError |= myValue> 31;

var pattern = /^\d{1,2}$/;
varexpr = newRegExp(pattern);

meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;

    });
//-----------end

//------------validate month
varmonthObject = formObject.find('#month');
monthObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
meError |= myValue< 1;
meError |= myValue> 12;

var pattern = /^\d{1,2}$/;
varexpr = newRegExp(pattern);

meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end
//------------validate year
varyearObject = formObject.find('#year');
yearObject.keyup(function () {
var me = $(this);
varmyValue = parseInt(me.val());
varmeError = isNaN(myValue);
varthisYear = new Date().getYear() + 1900; ;
var pattern = /^\d{4}$/;
varexpr = newRegExp(pattern);

expr = newRegExp(pattern);
meError |= myValue<thisYear - 100;
meError |= !(expr.test(myValue));

if (meError) {
me.addClass('red_bg');
me.parents('div.field').find('.info').fadeOut(100);
me.parents('div.field').find('.error').fadeIn(300);
        }
else {
me.removeClass('red_bg');
me.parents('div.field').find('.error').fadeOut(100);
        }
errorOccured = meError;
    });
//-----------end



//-----submit form----
//the user has clicked on the submit button, or pressed ENTER
formObject.submit(function () {
formObject.find('input').each(function () {
if ($(this).val() == '' || typeof $(this).val() == undefined || $(this).val() == null) {
errorOccured = true;
errorMessage += "All fields are required";
}
        });
return !errorOccured;
    });
//-------END

});

If you use Ajax to submit your forms, note that you can’t upload a file! I don’t trust Ajax!You should Maybeuse some special technics, such as adding an iFrame in your page and submit your image/file to this… please learn more Here

Conclusion

We have learnt how you can guide your users how to fulfill a form; you can use this concept to create your own form validation plugin. And I also know it is not easy to deal with regular expressions, so you just need to use the basic and common regex, which are easy to understand. Got a question? Write a comment or contact me by email. See you next week Use your imagination to satisfy your needs!



C# 4.5 Developer ASP.NET 4.5, Php 5, JavaScript (jQuery 1.6), Silverlight 4 (Sooner Beta5) xHtml, html5 Css 3 PhotoShop CS3 Java

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login