Javascript

Explain regex and write email validation

Here is an example of a regular expression (regex) for email validation using JavaScript:

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

This regex checks whether a string is a valid email address or not. Here’s a breakdown of how it works:

  • ^ indicates the start of the string.
  • [^\s@]+ matches one or more characters that are not whitespace or @.
  • @ matches the @ character.
  • [^\s@]+ matches one or more characters that are not whitespace or @.
  • \. matches a literal dot (.).
  • [^\s@]+ matches one or more characters that are not whitespace or @.
  • $ indicates the end of the string.

In plain English, this regex checks whether the string starts with one or more characters that are not whitespace or @, followed by an @ character, followed by one or more characters that are not whitespace or @, followed by a dot (.), followed by one or more characters that are not whitespace or @, and ends with one or more characters that are not whitespace or @.

You can use this regex with the test() method to check whether a string is a valid email address or not:

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const email = 'john.doe@example.com';
const isValidEmail = emailRegex.test(email);
console.log(isValidEmail); // true

In this example, we create a regex emailRegex and a string email that contains a valid email address. We then use the test() method of the emailRegex object to check whether the email string is a valid email address or not. Finally, we log the result to the console (true, in this case).

Being Idea

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

Share
Published by
Being Idea

Recent Posts

How to add meta query and modify WooCommerce product using all import plugin function

In this tutorial, I have write code to add custom meta query in main query…

6 years ago

Awesome checkbox and radio button styling with iCheck Bootstrap

In this tutorial we learn to customizing html checkboxes and radio buttons using twitter bootstrap.…

6 years ago

This website uses cookies.