How to check the correctness of the entered email using Javascript?

How to check the correctness of the entered email using Javascript?

Very often, before sending the form to the server, it is required to check the entered data, for example, if the user entered a name, email, set a password, if the passwords coincide (if we are talking about a simple registration form). Even a beginning JavaScript developer can write such a verification code. The difficulty may be caused only by checking the correctness of email address. If one checks the correctness of email using common checks, then we will see as the result a non-compact and inefficient code, overloaded with many if operators, and it does not necessarily mean that it will work correctly. For example, we all know that in any e-mail address there should be a symbol “@” and “.”, but if you check the presence of only these characters in a line, then obviously the check will not be complete. For example, we do not consider the following errors:

  • @john.sm@
  • .john@
  • .john@corp.
  • .j@cor.@

All these addresses can hardly be called correct. What are the variants? You can check that there is only one @ symbol in a line. But there are still a lot of wrong variants. For example:

  • john.corp@company
  • джон@corp.com
  • john@corp..

Not to overload the code with unnecessary checks, there is one way out - to use regular expressions. Only using regular expressions one can quickly and compactly check the correctness of e-mail. Let's write the function emailValidation (), which will check the correctness of email address:

 

function emailValidation(value) {

let txt = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

return txt.test(value);

}

Yes, the regular expression is very complicated, but it takes into account all possible variants of correct email construction and saves you from a lot of unnecessary checks.

It remains only to write the function checkEmail, through which we will transmit the contents of email text field to our emailValidation function. If it returns true, we display the message OK, otherwise we inform that the address is incorrect.

 

function checkEmail() {

let email = document.form.email.value;

if (emailValidation(email)) {

window.alert("OK");

} else {

window.alert("Email is incorrect");

}

}

You can a little complicate the task and check the address on-the-fly, after entering characters in the field. Therefore, we will rewrite the function checkEmail so that it displays the message about the correctness of the entered address in a specific element of the document. The result will be displayed in span. Here is the modified code:

 

function checkEmail() {

let email = document.form.email.value;

if (emailValidation(email)) {

document.getElementById('span1').innerText = 'OK';

} else {

document.getElementById('span1').innerText = 'Email is incorrect';

}

}

The function logic remains the same, only the way the result is displayed has changed. Everything else is a matter of technique. To check “on-the-fly”, use onKeyDown event for the input field:

<input type = "text" name = "email" id = "email" onKeyDown = "checkEmail ();">

Similarly, using this event, you can check the correctness of other form fields. For example, if the user indicated the phone number? Below there is the function to check the phone number in international format:

function phoneValidation(value) {

return /^\+\d{1,2}\(\d{3}\)\d{3}-\d{2}-\d{2}$/.test(value);

}

Please, note that functions of email and phone number verification check if the data entered by the user coincide with a particular pattern. They do not verify the existence of this email and phone number. For example, you can enter +55 (333) 044-99-44. This is the correct phone number, i.e. this number may exist, but if it exists, nobody knows. You can check the existence of email only by sending a message to this address, but no one does it. From a technical point of view, it is possible to perform this check: send an email, get a response from the server and issue a result. However, such checks cause unnecessary traffic.

Also on some websites it is possible to check not only the correctness of the entered data, but also their validity. For example, you entered email test@mail.ru when registering. From the point of view of the validation function, it is correct, because it corresponds to a regular expression. But this email may belong to another user who has already indicated it when registering. Unfortunately, Javascript cannot directly access the database to check if there is such an email in the database. Therefore, there are two ways:

  • Fix upon emailValidation function and send data to the server in case they look like the right ones. Further processing will be done by a program on the server (as a rule, this is PHP script).
  • Use AJAX technology that allows to call a third-party program for data processing. For example, our script will call PHP script that will check if this email was indicated when registering another user, and pass the test result to our JS script. Our script, based on the received response, will perform certain actions (it will inform the user that this email is occupied or free).

Popular Posts

My most popular posts

Maximum productivity on remote job
Business

Maximum productivity on remote job

I started my own business and intentionally did my best to work from anywhere in the world. Sometimes I sit with my office with a large 27-inch monitor in my apartment in Cheboksary. Sometimes I’m in the office or in some cafe in another city.

Hello! I am Sergey Emelyanov and I am hardworker
Business PHP

Hello! I am Sergey Emelyanov and I am hardworker

I am a programmer. I am an entrepreneur in my heart. I started making money from the age of 11, in the harsh 90s, handing over glassware to a local store and exchanging it for sweets. I earned so much that was enough for various snacks.

Hire Professional CRM developer for $25 per hour

I will make time for your project. Knowledge of Vtiger CRM, SuiteCRM, Laravel, and Vue.js. I offer cooperation options that will help you take advantage of external experience, optimize costs and reduce risks. Full transparency of all stages of work and accounting for time costs. Pay only development working hours after accepting the task. Accept PayPal and Payoneer payment systems. How to hire professional developer? Just fill in the form

Telegram
@sergeyem
Telephone
+4915211100235