- Email Validation in JavaScript
- Write Your Own Regular Expression
- 2. Use an npm Module
- 3. Use an API
- More Fundamentals Tutorials
- How to Do an Email Validation in JavaScript?
- Basics to Advanced — Learn It All!
- What is Validation?
- How to validate email using JavaScript
- Designing a Social Media App Like Instagram
- email.js
- email.html
- Input an email address
- Here’s How to Land a Top Software Developer Job
- email.css
- Output
- Get Ahead of the Curve and Master JavaScript Today
- Find our Full Stack Java Developer Online Bootcamp in top cities:
- About the Author
- Как сделать валидацию Email на Javascript
Email Validation in JavaScript
There are numerous solutions out there for validating an email address in JavaScript, depending on how strict you want to be with your validation. In this tutorial, you’ll learn about 3 different options and the tradeoffs between them.
Write Your Own Regular Expression
The quick and easy approach is to write a regular expression that validates whether a string is a correctly formatted email address. One simple approach I’ve used in the past is checking if the string looks like xx@yy.zz :
This regular expression is fairly concise and handles many common cases. If you don’t need to be especially strict about validation, this regexp can be helpful.
/^[^@]+@\w+(\.\w+)+\w$/.test('foo@bar.co'); // true /^[^@]+@\w+(\.\w+)+\w$/.test('foo.bar@baz.co'); // true /^[^@]+@\w+(\.\w+)+\w$/.test('foo@bar.c'); // false, TLD must be at least 2 chars /^[^@]+@\w+(\.\w+)+\w$/.test('foo@bar'); // false /^[^@]+@\w+(\.\w+)+\w$/.test('bar.co'); // false
However, there are many rules that the above regular expression doesn’t account for. For example, the «personal info» part of an email address (everything before ‘@’) cannot contain square braces [] . There are more sophisticated regexps that handle most of the edge cases, for example:
/^[-!#$%&'*+\/0-9=?A-Z^_a-z`<|>~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`<|>~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/
However, this regular expression still doesn’t handle all edge cases. For example, the personal info part of the email address cannot be more than 64 characters. Because of this, writing your own email validation regexp is typically not a good choice, unless you’re certain you only want a quick spot check as to whether an email is valid.
2. Use an npm Module
The email-validator npm module is a more robust check for whether a string is a syntactically valid email address. It handles several rules that regular expressions can’t check, for example:
const < validate >= require('email-validator'); validate('foo@bar.co'); // true validate('this-personal-info-is-too-long-it-must-be-less-than-64-characters@bar.co'); // false
The email-validator module is a great choice most of the time. It handles the complex regular expressions and various rules so you don’t have to. You should use email-validator or something similar, unless you have a compelling reason to write your own regular expression.
3. Use an API
Regular expressions and email-validator only check the syntax of the email address, not if it is an actual email address. For example, foo@bar.baz is a syntactically valid email address, but sending an email to that address from Mailgun will fail because baz is not a valid TLD.
There are several APIs for validating email addresses, like Mailgun and Kickbox. These APIs perform additional validation by talking to the actual mail server and verifying that the email exists.
For example, here’s how you can use Axios to validate an email against Kickbox’s validation API:
const email = 'notexist@karpov.io'; const apiKey = 'your key here'; const res = await axios.get('https://api.kickbox.com/v2/verify', < params: < email, apiKey >>); res.data.result; // 'undeliverable', because the email address doesn't exist
These APIs are also not foolproof: some mail servers don’t allow tools like Mailgun or Kickbox to check whether an individual email address exists, to block email scraping. However, if you want to make absolutely certain that users are signing up with valid emails, and you’re willing to pay to maximize deliverability, using an API is a good choice.
More Fundamentals Tutorials
How to Do an Email Validation in JavaScript?
JavaScript is an open-source programming language. It is designed for creating web-centric applications. It is lightweight and interpreted, which makes it much faster than other languages. JavaScript is used to create beautifully designed web applications.
Email validation in JavaScript is an important part of the user experience of a web application. Validation assists in inputting forms and makes sure that only valid information is passed to the server from the client-side of the application.
Basics to Advanced — Learn It All!
What is Validation?
Validation is commonly defined as the process of checking the values inputted by the user. It plays an important role in web applications and enhances the overall user experience. We can validate email, password, date, mobile numbers, and many other fields.
JavaScript is used to validate the form data on the client-side of a web application, and this speeds up the validation process because of faster data processing when compared with server-side validation.
Now that we know a bit about validation, let’s go ahead and implement email validation in JavaScript.
How to validate email using JavaScript
Email validation is a critical part of validating an HTML form. An email is a string or a subset of ASCII characters separated into two parts by @ symbol. The first part contains personal information while the other contains the domain name at which the email is registered.
The personal information part can contain the following ASCII characters:
- Uppercase and lowercase letters (A-Z and a-z)
- Numeric characters (0-9)
- Special characters — ! # $ % & ‘ * + — / = ? ^ _ ` < | >~
- Period, dot, or full stop (.) with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.
Designing a Social Media App Like Instagram
One of the most popular ways of validating email in JavaScript is by using regular expressions. JavaScript uses regular expressions to describe a pattern of characters.
email.js
This file contains the JavaScript code that we need for email validation. We are using regular expressions to validate the email at the client-side of a web application.
alert(«Invalid email address!»);
- Define a regular expression for validating email address
- Check if the input value matches with regular expression
- If it does match, send an alert stating “valid email address”
- If it doesn’t match, send an alert stating “invalid email address”
email.html
This file contains the base HTML code that has all the elements defined for this webpage.
Input an email address
Here’s How to Land a Top Software Developer Job
email.css
This file contains the CSS styles that are needed for styling the HTML elements in the webpage. The styles are self-explanatory and you are free to change these styles according to your preference.
Output
The output should look and feel like this in the end.
Fig: Email Validation in JavaScript
We hope you understood how to implement email validation in JavaScript after going through this article. This is a relatively simple topic that gets used in various kinds of web applications.
Get Ahead of the Curve and Master JavaScript Today
Are you wondering how you can gain the skills necessary to take advantage of JavaScript’s immense popularity now that you are familiar with email validation? We have got your back! We offer a comprehensive Java Certification Training, which will help you become career-ready upon completion. Also email validation is one of the commonly asked topics in the Java interview questions. So, get started today and seize your future!
If you’re an aspiring web and mobile developer, JavaScript training will broaden your skills and career horizons.
Do you have any questions for us? Please mention it in the comments section of this ‘Email Validation in JavaScript’ article and we’ll have our experts answer it for you.
Find our Full Stack Java Developer Online Bootcamp in top cities:
Name | Date | Place | |
---|---|---|---|
Full Stack Java Developer | Cohort starts on 4th Aug 2023, Weekend batch | Your City | View Details |
Full Stack Java Developer | Cohort starts on 25th Aug 2023, Weekend batch | Your City | View Details |
About the Author
Taha Sufiyan
Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.
Как сделать валидацию Email на Javascript
Есть текстовое поле, куда пользователь должен вводить E-mail.
Первым делом добавляем input в HTML. Здесь все просто:
Для простоты восприятия предположим, что больше на странице ничего нет, поэтому не станем добавлять лишние атрибуты.
Так как подсветка должна меняться в реальном времени, добавим «слушатель» на input :
const input = document.querySelector('input'); input.addEventListener('input', onInput);
Функция onInput будет менять цвет css-свойства border на зеленый, если введенный в input текст валиден, или на красный — если нет.
const EMAIL_REGEXP = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"])$/iu; const input = document.querySelector('input'); function onInput() if (isEmailValid(input.value)) input.style.borderColor = 'green'; > else input.style.borderColor = 'red'; > > input.addEventListener('input', onInput); function isEmailValid(value) return EMAIL_REGEXP.test(value);
Функция isEmailValid будет сравнивать введенное пользователем значение с регулярным выражением. В успешном случае функция вернет true , иначе — false .
Вот и все! Скрипт готов. Его работу вы можете проверить в моем Codepen.