How to validate an email address using JavaScript

Validating email address using regular expressions is tricky and is often not recommended. The reason is simple. A valid email address as defined by RFC 2822 can be quite complex.

A valid email is of the format:
name@domain

The name can be a set of ‘atoms’ separated by dots. In its simplest form like this:
john.doe@domain

now, the atoms can contain
1. alpha-numeric characters
2. Any of these characters
! $ & * - = \^ ` | ~ # % ‘ + / ? _ { }
3. single or double quotes and any character inside the quotes

Now, to the domain part.
Most email validation checks assumes that the top level domain can have up to 4 characters. It is not true. There are TLDs like this: .MUSEUM .travel, .international or even .vermögensberatung

For example all the following email addresses are valid:

  • あいうえお@a.long.domain.example.university
  • one.“more\ long”@example.website.place
  • customer/department@example.com

Writing a email validation that validates for all those cases is difficult but possible.
Here is an email suggested from this post:

A near perfect Javascript Email validation regex

Source

The purpose of the validation

The sad truth is that despite the complex regular expression validation, the email may not be existing, so can still be invalid for practical purposes. You have just validated the format – not its existence.

The only way to truly validate the email address is to send an email to that address and request the user to confirm by clicking on a unique link (or entering a confirmation code)

Remember, if the user’s intention is to enter an invalid email address, she can do it so easily whether you have the most tough validation or not.

The whole purpose of the Javascript email validation should be to check for any unintentional error (like entering name instead of email).

A simple, practical Javascript email validation

The simple, future proof email validation test would be to check the presence of @ symbol

Just use HTML5 email input field

This would be the easiest and best option at the moment. Make use of the HTML5 email input element like this:

Also see:

Further Reading and References

HTML submit button onclick code

An HTML button is created using the following HTML code:

Or using the button tag like this:

In both the cases, pressing the button will submit the parent form without the need for handling the onclick event separately.

If you want to validate the form before submitting, the best event handler would be the onsubmit event of the form.
Example:

22934

Returning false from the onsubmit event handler of the form stops the form being submitted.

So the submit button has a meaningful existance only within a form

If, you want a plain simple button that triggers an event when the button is pressed/clicked, use the button tag with type=submit like this

Examples of javascript form validation using regular expressions

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 :

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

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

Now let’s move on to the Postal code part.

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.

Now let’s jump to the regular expression itself:

UK postal code examples :
EC1A 1BB
W1A 0AX
M1 1AE
B33 8TH
CR2 6XH
DN55 1PT
So, 1 or 2 alphabetic characters, followed by 1 or 2 digits, then a space and one digit and exactly two alphabetic characters.
So here is the Regular expression pattern:

/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i

The i at the end of the pattern is to indicate that this is a case insensitive match.

Here is the demo code:

22934

Now that we have got the patterns right, we can go ahead and add this code to the validation function of the form:

More Regular Expression Checks

  1. Date
  2. /^\d{2}\/\d{2}\/\d{4}$/
    This simple regular expression just checks for 2 digits / 2 digits / 4 digits date format

    If you want more complex, tight validation for mm/dd/yyyy format, here is the format
    /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/

    source

  3. URL
  4. A URL of the format http(s)://website/page can be validated with this regular expression:

    https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

    source

  5. Any Alpha Numeric String
  6. If you want to allow only alphanumeric characters, use this regular expression:
    /^[a-zA-Z0-9]*$/

  7. Decimal Numbers
  8. For decimal numbers with one decimal point, the regular expression is:
    /^[0-9]+\.?[0-9]*$/

How to handle HTML checkbox events

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

  1. How to handle onclick and onchange events and the difference between them
  2. How to handle checkbox events in Jquery
  3. How to submit a form when checkbox is clicked
  4. 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.

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.

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

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.

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 :

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 :

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.

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.

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 .

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

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 :

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’) .

HTML input type password field – example code and techniques

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

  1. create a password input field and style it
  2. add a button that can enable the user to view his password in plain text
  3. add validation to your password input field
  4. 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

22934

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.

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.

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.

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

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

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.

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.

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

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.

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.

How to Create a Telephone Input Field in HTML5

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”:

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:

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.

22934

How to Use Html5 Input Type Email

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.

Sample Code:

[click to continue…]

How to Add a Label to HTML Radio Button

Radio button allows user to choose only one of the pre-defined options. Each radio button must be accompanied by a label describing the choice it represents.

There are two ways to label radio button elements. One is to enclose the whole <input type=”radio”> tag inside <label > tags:

[click to continue…]

How to Create a “Yes/No” Radio Button

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

Here is the code to create a yes/no radio button.

[click to continue…]

How to Customize HTML5 Date Field Date Format

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…]