Learning Regex by creating an Email Password validator
JavaScript Mini-Project
Introduction
As we all know, developers need to learn regular expressions (or Regex). A regular expression is a sequence of characters that specifies a search pattern in text. It is mainly used for "find" or "find and replace" operations or for input validation.
Building something with Regular Expressions
Recently I started learning Regex using YouTube video tutorials. I used this tutorial series from The Coding Train to really wrap my head around this concept, which is often confusing for many people:
So I decided to create a simple webpage which uses regular expressions to validate user input on the front-end. Of course, this is not best practice; you should always validate user data on the back-end as well, but this is just for playing around with regex.
Email validation
I created an input field where the user can type in the email, then updated if it is valid or not with each keystroke (using some DOM manipulation).
I used this regular expression:
const regex1 = /^\w+\.?\w+?@\w+\.(com|org|net|edu)$/;
This basically matches
- one or more word characters at the beginning of the match
- followed by an optional dot(.)
- followed by as few as possible word characters
- followed by an @ symbol
- then one or more word characters
- then a dot(.)
- and finally ending the match with either com, org, net or edu
Password validation
This was much more complex than I thought. The UI was basically the same.
The regex used was:
const regex2 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*\-_+=?]).{8,}$/;
This helped to write the expression:
Final Result
Finally, I added some basic styling.
This is what the page looks like
Learn More
You can learn much more about regex at Regexr
Thanks