You just need to create a new Regex object and use the provided methods that come on that object to run a search against a provided string. Let's take a look.
This creates a new Regex object using the regular expression for email validation that we just broke down and assigns it to a variable called emailRegex. Note that we pass the modifiers in a the second argument to the constructor.
The Javascript Regex object provides a method called test that accepts a string input and tests it against the regular expression you provided. If the input string is a positive match, the test method will return true. If not, it will return false.
That's it!
Alternative Email Validation Using an API
As we've discussed, you shouldn't use a regular expression to validate an email in Javascript. It is not a robust enough method and will not catch all possible email addresses. Not only that, there are literally hundreds of libraries and packages and APIs out there that will do email validation for you.
Let's look at the AbstractAPI Free Email Validation API as an alternative solution.
Get Started With the API
In order to use the API, you'll need to sign up and get an API key. The API key authenticates you with the API and allows you to make requests.
Navigate to the API home page and click "Get Started"
You'll be asked to sign up with an email address and password. Once you've done that, you'll land on the email API dashboard, where you'll see your API key, links to documentation and pricing modules, and a testing sandbox.
Copy the API key. We'll need it in our Javascript code.
Send an Email Validation Request to the API
Inside your Javascript code, create a function called sendEmailValidationRequest.
This function will accept an email address as its argument. It will send an AJAX request to the API endpoint with the email for validation. It will then receive and analyze the response and return a boolean value.
The response from the API will look something like this:
There's a lot of information. For now, we're only interested in the is_valid_format field. The sendValidationRequest function will pull out the value from this field and return it as the result of our function.
Let's take a look at the code:
This will return false if the email address provided is an invalid email address. If the email validation is successful, it will return true.
Note that the function is an async function, because we are sending a network request. We can improve this somewhat by adding error handling.
This is a very easy way of validating email in your Javascript app.
The AbstractAPI endpoint does a lot of checks when it receives your email. As well as running a much more sophisticated regular expression check on the email, it also checks for syntax errors and typos in the email address (for example john@agmil.com), does real-time SMTP and MX record checks against the email's domain, and uses a variety of filters backed by machine learning to detect risky emails.