In this tutorial you will see how to use regular expressions to validate. Through a list of examples , we will build a script to validate phone numbers , UK postal codes, along with more examples.

First, let’s start by building the webpage and the validation code then we will talk about the regular expressions used to validate the strings. First go to your html file and paste the following code :

XHTML

1

2

3

4

5

<form action=""onsubmit="validate()">

<input type="text"id="phone-number"placeholder="phone number"/><br>

<input type="text"id="postal-code"placeholder="postal code" /><br>

<input type="submit" />

</form>

Here, I have a simple form. It has an onsubmit event attached to a function called validate() that we are going to create later inside this form there are three inputs one for our phone number another one is for postal codes and the third and the last one is a submit button that is going to submit the form after we are done filling it.

Now let’s jump to the javascript code which will contain all the regular expression parts .

This is our validate() function for now. It contains only the code that validates the phone number. In the first line, I am using document.getElementById() to grab the phone number from the input element. Then I created my regular expression and attached it to a variable called phoneRGEX notice that I did not need to wrap the regular expression in quotes this is because javascript natively recognizes regular expressions so there is no need to create them as strings then convert them.

Then I created a variable that contains the result of running the test() function on the phoneNumber string which will be a boolean that contain either true if the string matches our regular expression or false if it does not.

Now let’s jump into the fun part which is discussing the regular expression

JavaScript

1

/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/

First we have the starting and ending slashes “/” , the expression then starts with a “^” sign
to match with the beginning of the string. Notice the [-\s\.] this part matches a hyphen(-) space or a dot (.).[0-9]{3} means 3 digits. So basically the expression tries to match with a phone number like this
(541) 754-3010
or like this
541-754-3010
or with spaces

Here I have added a new variable called postalCode to fetch the postal code from the form then
created another variable to store the postal code regular expression which we will be discussing in a second.
Then I used the test function to test my string against the regular expression and print the result in an alert.

The HTML checkbox input element allows you to select a single value for submission in a form for example if you are creating a form and want to know if the applicant is fluent in English or not you can have a checkbox and if the user thinks he/she is fluent in English he/she checks it if not leaves it unchecked .

In this tutorial we are going to learn

How to handle onclick and onchange events and the difference between them

How to handle checkbox events in Jquery

How to submit a form when checkbox is clicked

Show/ Hide a section of the form when checkbox is clicked

To start working with checkboxes we will create a form that contains a checkbox , in this example we will be building a form that takes the a user name and has also a checkbox that the user should check if he thinks he is fluent in English , if not a prompt will appear showing the user a text that says you need to be fluent in English to apply for the job.

XHTML

1

2

3

4

5

6

<form action="">

<label for="name">Name:</label>

<input type="text"name="name"><br>

<label for="language">Do you speak English fluently?</label>

<input type="checkbox"id="fluency"checked />

</form>

Checkbox event handling using pure Javascript

22934

Now what we need to do is to attach an event to the checkbox so it checks it’s state each time it’s changed and show the message if it has been unchecked , notice I added a checked property to the checkbox so it is checked by default.

There are two events that you can attach to the checkbox to be fired once the checkbox value has been changed they are the onclick and the onchange events.

There is a problem with the onchange event is that it is not called until the checked state has been updated and since Internet Explorer does not fire the onChange event till the checkbox loses focus so it will create different results than in Google chrome and other browsers so to avoid all this I recommend you stick to the onclick event.

XHTML

1

<input type="checkbox"onclick="checkFluency()"id="fluency"checked />

Here I added an on click event and make it so it will call a function called checkFluency() once it is clicked

JavaScript

1

2

3

4

5

6

7

8

functioncheckFluency()

{

varcheckbox=document.getElementById('fluency');

if(checkbox.checked!=true)

{

alert("you need to be fluent in English to apply for the job");

}

}

Here in the checkFluency() function , picked the checkbox and then if it is not checked an alert is shown saying “you need to be fluent in English to apply for the job”

Using jQuery

22934

We could have done the same thing using jQuery and in fact that is what we are going to be doing next .
jQuery is the most famous JS library ever created , and a lot of people use it daily as it makes their job a lot easier . You do not need to worry if you do not know jQuery , it’s concepts are very easy and I will be explaining everything as we go along.

I only added jQuery and couple of CSS lines to style our page.
I also added the same exact HTML code we used in the previous code , the only difference will be in our javascript code since in this example we will be using jQuery instead of plain javascript.

XHTML

1

2

3

4

5

6

<form action="">

<label for="name">Name:</label>

<input type="text"name="name"><br>

<label for="language">Do you speak English fluently?</label>

<input type="checkbox"name="fluency"id="fluency"checked/>

</form>

You may notice that the only thing I changed from the previous example is that I have deleted the onclick event in the checkbox which makes sense , since in jquery we will be attaching the event to the element no need to call it from the HTML code.

Now to the javascript code where all the magic happens :

JavaScript

1

2

3

4

5

6

7

8

9

10

$(document).ready(function()

{

$('#fluency').change(function()

{

if(this.checked!=true)

{

alert('you need to be fluent in English to apply for the job');

}

});

});

If this seems overwhelming to you , no need to worry , I will be explaining everything in details. First, I am using the $(document).ready(); that I have told you about and inside it I added an anonymous function.

If you are not familiar with anonymous functions they are functions that are declared in runtime and the reason they are called anonymous is that you create them without giving them a name.

And inside the anonymous function I placed the following code :

JavaScript

1

2

3

4

5

6

7

$('#fluency').change(function()

{

if(this.checked!=true)

{

alert('you need to be fluent in English to apply for the job');

}

});

First, we are using the dollar sign ‘$’ which is a shorthand for jQuery so this $(‘#fluency’) is the same exact thing as jQuery(‘#fluency’). Then we are attaching to it an on change event and inside it we are using the anonymous function syntax for the second time. The code that is inside the anonymous function will be run each time the event is fired.

JavaScript

1

2

3

4

if(this.checked!=true)

{

alert('you need to be fluent in English to apply for the job');

}

This is the same exact if statement we used in the first example with only a very small change , which is instead of getting the checkboc using document.getElementById() we are using the “this” keyword.
If you are not familiar with the ‘this’ keyword , here in this example it refers to the target that fired that event which is here the checkbox we want to grab.

Submitting the form when checkbox is clicked

Sometimes you might want to submit the form just when the user clicks a checkbox, rather than making the user press the submit button.

All what we will have to do is give an id to the form , I gave it an id of myform, then use jQuery to grab and submit the form.

JavaScript

1

2

3

4

5

6

7

$('#fluency').change(function()

{

if(this.checked==true)

{

$('#myform').submit();

}

}

Hide/show elements when checkbox is selected

22934

I am sure most of you have seen a lot on the Internet which is when there is something hidden in the form , something like a section for extra information or feedback and you press on a checkbox to toggle it and show it or hide it . And this is what we will be building. We are going to be using jQuery because it will be much easier and shorter and I do not want you to get lost in a lot of lines but this example can be done with only javascript and it will not be hard .

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

<div>

<form action="">

<input type="text"name="name"placeholder="name">

<input type="email"name="email"placeholder="abcd@abcd.com" >

<label for="more-info">show more info</label>

<input id="more-info"name="more-info"type="checkbox">

<div id="conditional_part">

<textarea name="message"cols="30"rows="10"></textarea>

</div>

</form>

</div>

In the code above we have a div and inside it we have a form that contains a text with a placeholder text of name which will contain the name of the applicant , another input with type e-mail , checkbox and a text area .
When the checkbox is checked the textarea should appear so by default it should be hidden.
So we make the container div (with id conditional_part) hidden

CSS

1

2

3

4

#conditional_part

{

display:none;

}

Next step is creating the javascript which is going to make this textarea appear and disappear .

The javascript for this example is pretty straight forward :

JavaScript

1

2

3

4

5

6

7

8

$('#more_info').change(function(){

if(this.checked!=true){

$("#conditional_part").hide();

}

else{

$("#conditional_part").show();

}

});

Here, we are first grabbing the checkbox which we gave an id of more-info and attaching to it an onchange event that fires an anonymous function when the event is fired.

Inside this anonymous function we are having the same if statement we used in the previous example to check whether the checkbox is checked or not. And inside them we are using the jquery hide() and show() functions . These functions simply change the display type of the div (with id ‘conditional_part’) .

The HTML <input type=”password”> element is a specific type of input elements used to create input fields that deal with passwords . It is designed to deal with passwords so it’s more secure than the normal <input type=’text’> we see in every form on the internet.

First: It makes the password not visible to anybody sitting around you by showing “.” or “*” instead of the characters you type.

Second: Browsers treat inputs with text type and password types differently , browsers may try to automatically refill the text input types if they have been previously entered which is something you may not always want.

HTML <input type=”password”> element is where you should make the user type their password in , and in this article we will know how we can customize the password input fields to accommodate our needs.

By the end of this tutorial you will know how to

create a password input field and style it

add a button that can enable the user to view his password in plain text

add validation to your password input field

create a numbers only password field

Creating a password input field is as simple as typing <input type=”password”> and it will come packed with every thing we need as hiding the password and replacing it with dots.

Now it’s time to add some logic to our example here , we will create an eye icon that you can click to show
the password and click again to hide it.

Show/Hide Password Mask

Here all what I have done is created a div that contains the password input field and it has an id of “password-field” which we will use later to give it style and reference it in our javascript file next we created an I element with class “fa fa-eye” and id of “pass-status” which will create an eye icon using fontawesome

Note: if you are not familiar with font awesome do not worry it’s a simple font that contain many icons that are used allover the web as they are very easy to style.

We also added an onClick event to our icon that calls a function called viewPassword each time it is clicked . Here is the final result so far do not worry if yours looked different you can copy all the css from our codepen

Now we need to create the javascript code to check if the password is already hidden view it and change the icon to a crossed eye.

JavaScript

1

2

varpasswordInput=document.getElementById('password-field');

varpassStatus=document.getElementById('pass-status');

To make this example work we need to check first to see if the password is hidden and view it also change the icon to match the view state. To do all this we will use a small trick , we know that what makes our password hidden is the use of “password” as a type for our input so all what we will have to do is when the icon is clicked we will check if our input had a type of “password” we will change it to type “text” which will lead to showing the password till the user click again on the icon.

JavaScript

1

2

3

4

5

6

7

8

9

10

if(passwordInput.type=='password')

{

passwordInput.type='text';

passStatus.className='fa fa-eye-slash';

}

else

{

passwordInput.type='password';

passStatus.className='fa fa-eye';

}

Remember all this code is written inside the viewPassword() function. All what we are doing here is using an if statement to check if our password input’s type is “password” then change it to text and change the class of the icon’s class to
“fa fa-eye” which is the class for a slashed eye in font awesome. If the input had already a text type which means the icon has already been clicked we will reverse everything we have done by changing the input type back to password and the icon class name to “fa fa-eye” which will make the password hidden again and will make .

Checking for Password Strength

22934

Enabling the user to show and hide his password is not all that we can do , a study has show that one each fiver users use 123456 as their password which is very unsafe and all the fancy stuff website developers do nowadays from hashing to salting all of this will not make any difference if the hacker can simply guess your password and if you use any in the list of top famous 25 password , there is a pretty good chance the hacker may be able to guess it right. One way we can solve this issue is to add validation to your password input for example force your user to create a password that contain at least one letter , one digit and 8 characters. And this is exactly what we will do now.

XHTML

1

2

3

4

5

<div class="second-example">

<input type="password"id="password-2"onkeyup="validate();">

</div>

<div id="validation-txt">

</div>

Here we did the same as the first example we created a div with a class of “second-example” and added in it a password input with an id of “password-2” and I added an onkeyup event and made it’s value equal to a validate() function .

Note : we used here onkeyup event because onkeydown will fire the event once the key is pressed before even the character is typed on the screen which will lead to a problem causing the password to not be written.

We also added a div with an id of “validation-txt” that will contain all the warning that we will display to the user.

Now we need to create the javascript that will make all this happen. First we create the function validate() that will contain all our code

JavaScript

1

2

3

4

5

6

7

8

functionvalidate()

{

varvalidationField=document.getElementById('validation-txt');

varpassword=document.getElementById('password-2');

varcontent=password.value;

varerrors=[];

}

In the code above we used document.getElementById to grab the password input and the validation div that will contain all our warnings . We also created a variable called content and we assigned it to password.value which is the value of out password input field , we also created an empty array that will contain all our validation errors to be able to view them to the user.

Next we need to start validating the password each time a character is typed and check if it satisfies our validation conditions or not.

As I mentioned before we will check if the password’s length is greater than 8 characters and if it contains at least one litter and one digit.

We will start by the easiest one which is checking that the password is longer than 8 characters

JavaScript

1

2

3

4

if(content.length<8)

{

errors.push("Your password must be at least 8 characters");

}

Here, we are using the length property to check if our password has less than 8 characters and if it does we are using the push function to push the string “Your password must be at least 8 characters” to the errors array we created before.

Next we need to check if the password field contains at least one letter , unfortunately there is no native way we can do this easily in javascript so we will have to use regular expression or as sometimes called “regex”. Do not worry if you are not familiar with regular expressions or never heard of them before , regular expression is a special string that describes a search format , we can use it to search for a phone number in a long document by just knowing it’s format 998- 902-142. Here we are going to use it to check once if the password contains at least one letter and if it contains at least one digit.

JavaScript

1

2

3

4

5

6

7

8

if(content.search(/[a-z]/i)<0)

{

errors.push("Your password must contain at least one letter.");

}

if(content.search(/[0-9]/i)<0)

{

errors.push("Your password must contain at least one digit.");

}

Here we are using the search function which is a special regular expression function built natively to javascript to check a regular expression term against a string. Here “/[a-z]/i” means that the search function will be searching for any character from a to z and “/[0-9]/i” will search for any digit between 0 and 9 and if it does not wound any it uses the push function we have talked about earlier in this tutorial to add the warning string to the errors array.

The last thing we need to do is to add the errors we collected in our errors array to out html.

JavaScript

1

2

3

4

5

6

7

if(errors.length>0)

{

validationField.innerHTML=errors.join(',');

returnfalse;

}

validationField.innerHTML=errors.join(',');

returntrue;

Here we are using an if statement to check if the number of elements in the array are greater than zero which means there has been validation errors then we use the join function to attach all the elements of the array together in one string separated by the “,” comma sign then adding our results to the html in the validation div we have created.

“Digits only” Password field using CSS

22934

The last thing we are going to learn about in this tutorial is how to make a password input field that accepts numbers only. This is very useful for example if you are trying to create an input field for a pass code that needs to be only in numbers and want the mobile users to automatically see the number pad once the click on the input field .

This time we will not be creating a password input field , we are going to be creating a numeric input field instead

XHTML

1

<input type="number"id="password-3"pattern="[0-9]*" >

Here we created an input element with a type of number and added pattern=”[0-9]*” this is supported in safari and most browsers and will make the number pad in the mobile phone pop up automatically once the input field is in focus.

What is remaining now is to hide the password to make it look like other password inputs that we have made and remove the number spinner that appears by default in a lot of browser. Fortunately this is very easy using CSS 3.

CSS

1

2

3

4

5

6

7

8

9

10

#password-3{

-webkit-text-security:disc;

-moz-text-security:circle;

text-security:circle;

}

input[type=number]::-webkit-inner-spin-button,

input[type=number]::-webkit-outer-spin-button {

-webkit-appearance:none;

margin:0;

}

In the first part, we are using the id of the input element to hide the password and replace it with the dots like other input field with type of password and the second part we are changing the style of every input element with type number to change the outer and inner spinners that sometimes appear natively in some browsers to enable users to increase and decrease numbers.

Though field validation and data formatting are the biggest challenges of working with web browsers, HTML5 does some help in enforcing this for us.

Telephone input field can be created using type=”tel”:

XHTML

1

2

3

<input type="tel"

name="phone_num"

id="phone_num"/>

This looks like every other input field, with the difference that it optimizes the keyboard. Certain platforms like tablets, or smartphones will pop-up only-numeric keyboard for this input field.

It is hard to enforce particular regular expression through HTML because of variety of phone number formats used along with differences in country codes, and number separators. It remains the sole responsibility of the developer to implement these checks through JavaScript or other library function.

For example, here is the pattern for common USA phone format:
[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}

you can apply this format using the pattern attribute:

XHTML

1

2

3

4

5

<input type="tel"

name="phone_num"

id="phone_num"

pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}"

/>

This page has some more examples for phone number patterns in different regions

tel input type is currently supported in all major modern browsers. The full numeric keypad makes a great user experience.

Before the advent of HTML5, handling emails addresses required more work to validate the email addresses using Javascript. Well all that is now not necessary with the new HTML5 input type email.

The email input element has been specifically designed to handle and validate email addresses. Depending on the browser, it will alert the user that the entered information is not correct and the form will not submit until the user makes corrections.

Using radio button to accept Yes/No questions is best because the field accepts only one of the options. It is better than a dropdown because there are only two choices – either of them can be selected by a single click

When date input was added by HTML5, many believed that it would offer the users a friendly, interactive and known method of entering a date on a website. However; this new addition has failed to live up to the expectations and the major reason behind it remains the fickle nature of the format of the input given by the user.

Originally, the date input attribute was designed as a form element to pick values through a datepicker. The problem however, lies in the implementation of datepicker which changes from browser to browser. What it essentially means is that as a web designer you must be intending to allow user to pick a date in the format YYYY/MM/DD via datepicker and you designed your HTML validations accordingly, but when the user accesses the webpage through the browser on his system, he might see a completely different sequence of selections depending upon the default date settings in his/her system and the browser used.

Now there is no said rule in HTML5 that would allow the web designers to change the format in which the date element picks values. Therefore, the rigidness of the date element prompted designers to look for other ways to alter the format of the date to be entered by the user.[click to continue…]

The CSS3 “hover” is a pseudo-class that enables you to select and style elements on a web page when the mouse moves over an element. You can use Javascript or CSS style sheets to react to this event depending on your objective. For example:

CSS

1

2

3

4

5

6

7

8

9

button.checkout

{

background-color:blue;

}

button.checkout:hover

{

background-color:green;

}

The CSS code above styles a button with class ‘checkout’. The default color of the button is blue and when the mouse is over the button, the color changes to green.[click to continue…]