Slater New
« back to Blog

Javascript 101: rrrrregex

Jared Malan
Director Of Technology
 @
Edgar Allan

Regex or Regular expression is a powerful tool that allows you to search, validate, and manipulate text based on patterns. Regex is widely used in various programming languages and is particularly useful for tasks like form validation. (Before AI, using Regex was an absolute nightmare but with AI assistance, 😍.) In this 101, let's focus on using regex to validate a user's email address.

Need to validate phone numbers, websites or LinkedIn Urls? Check out the Community Library.

What are Regular Expressions? A regular expression is a sequence of characters that defines a search pattern. This pattern can be used to match, locate, or manage text. Regex is language-agnostic, meaning you can use similar patterns in JavaScript or most other languages.

Let's examine a JavaScript function (also found in the community library) that uses regex to validate email addresses:

function validEmail(email) {
 const re =
   /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

 return re.test(email);
}

Want to know what the Regex does? I'll translate a bit to get a sense of how Regex works but we won't be exhaustive:

  • ^: Asserts the start of the string.
  • ([^<>()[\]\.,;:\s@quot;]+(\.[^<>()[\]\.,;:\s@quot;]+)*): Matches the username part of the email.
  • |: Or operator.
  • The username can also be: quot;.+quot;: Anything inside double quotes (for emails with spaces or special chars).
  • ...

🤯 Had enough? Use Slater AI to write your Regex.

Here's how you might use this in a web form:

function validEmail(email) {
 const re =
   /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

 return re.test(email);
}

$("#email-el").on("blur", function () {
 let email = $(this).val()

 if (!validEmail(email)) {
   // This email is invalid. Throw an error.
 }
})

If you add this to a form, you can run the following tests email and see how the regex responds:

Regex is great for validating user input but it can do so much more. Maybe we can dig into another use case in a future 101.

Want to test your regex, check out a playground like https://regexr.com.

Keep exploring regex! It's a skill that will serve you well in the Webflow world.

Try it out for yourself

Sign up for a free trial and see if Slater is for you.

Share this post

We are building a first-class development experience that bridges together code and no-code.