Email regex in javascript

Validate Emails using Regex in JavaScript

To validate emails using a regular expression, you can use the match function with one of the two following regular expressions. The match() function will return a truthy value if there is a valid email address in the given input string.

/(?:[a-z0-9+!#$%&'*+/=?^_`<|>~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`<|>~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:253|219|[01]?14?)\.)(?:252|237|[01]?96?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i

The first regular expression is much simpler and more concise. It ensures that you have a sequence of non-whitespace characters, followed by an @ , followed by more non-whitespace characters, a dot, and more non-whitespace.

Below is a live example that lets you test email addresses using the above regular expressions.

 input id="example" type="email"/> div> button onclick="verifyEmail1()">Verify Email with Regex 1 button> button onclick="verifyEmail2()">Verify Email with Regex 2 button> div> div> p id="result"> p> div> div> function verifyEmail1( ) < const input = document.querySelector("#example"); const display = document.querySelector("#result"); if (input.value.match(/[^\s@]+@[^\s@]+\.[^\s@]+/gi)) < display.innerHTML = input.value + ' is valid'; > else < display.innerHTML = input.value + ' is not a valid email'; > > function verifyEmail2( ) < const input = document.querySelector("#example"); const display = document.querySelector("#result"); if (input.value.match(/(?:[a-z0-9+!#$%&'*+/=?^_`<|>~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`<|>~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:253|225|[01]?98?)\.)(?:254|226|[01]?65?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gi)) < display.innerHTML = input.value + ' is valid'; > else < display.innerHTML = input.value + ' is not a valid email'; > > /script>

More Fundamentals Tutorials

Источник

Как сделать валидацию Email на Javascript

Как сделать валидацию 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.

Источник

Validating email addresses using regular expressions in JavaScript

Email addresses are a critical part of online communication, and ensuring that the email addresses entered by users are valid is an important task for any web application. In this blog post, we will discuss how to use regular expressions in JavaScript to validate email addresses according to the rules specified in the official RFC 5322 standard. First, let’s take a look at the regular expression that we will use for validation:

This regular expression may look daunting at first glance, but it is actually composed of several smaller, simpler regular expressions that are combined to form a complete email address validation pattern. Let’s break it down:

The first part of the regular expression matches the local part of the email address, which consists of the username and the domain name (e.g. john.doe in john.doe@example.com). This part of the regular expression allows the local part to contain letters, numbers, and a few special characters (., !, #, $, %, &, ‘, *, +, /, =, ?, ^, _, [backtick], , ~, and -).

The next part of the regular expression matches the domain name of the email address (e.g. example.com in john.doe@example.com ). This part of the regular expression allows the domain name to contain letters and numbers, and allows for the use of internationalized domain names (IDN) by allowing the use of hyphens ( — ) within the domain name.

The final part of the regular expression matches the top-level domain (TLD) of the email address (e.g. com in john.doe@example.com ). This part of the regular expression allows the TLD to contain letters and numbers, and allows for the use of IDN TLDs by allowing the use of hyphens ( — ) within the TLD.

Now that we have a thorough understanding of the regular expression, let’s see how we can use it in a JavaScript function to validate email addresses. First, we will define a function called validateEmail that takes an email address as an argument:

function validateEmail(email)  // Validation code goes here > 

Get 40% off premium Skillshare membership

Next, we will use the test method of the emailRegex regular expression to check if the email address passed to the function is a valid email address according to the pattern defined in the regular expression:

function validateEmail(email)  return emailRegex.test(email); > 

Finally, we can use the validateEmail function to check if a given email address is valid by passing it as an argument to the function:

let email = 'john.doe@example.com'; if (validateEmail(email))  console.log('Valid email address'); > else  console.log('Invalid email address'); > 

That’s it! With just a few lines of code, we have implemented a reliable email address validation function using regular expressions in JavaScript. As always, it’s important to keep in mind that while this method is effective, it is not foolproof and should be used in conjunction with other validation techniques to ensure the security and reliability of your web application.

At the end of this blog post, I want to thank all of my readers for following along and for their support. I’m grateful for the opportunity to share my knowledge and experiences with you, and I hope that my posts have been helpful and informative. If you are a self-taught full-stack developer, you should read my ebook. It will guide you on your journey and provide you with a clear and «real» path to success:
The Self-Taught Full Stack Web Developer’s Journey: A Comprehensive Guide to Success Finally, don’t forget to follow me on Twitter for updates on new blog posts and other interesting content. Thanks again for your support and I look forward to continuing to share my knowledge with you.

Источник

Читайте также:  How to debug in java
Оцените статью