How to use regex and vue to validate form input

I haven’t talked about regular expressions much on this blog and that is mainly because I don’t feel like I understand the topic enough.  We are going to work on that, today.  Regular expressions (or regex) are patterns used to match character combinations in strings.  There are regex strings to test for valid phone numbers, email addresses, IP Addresses, credit card numbers, and much more.  In today’s post I figured that we would look at three examples of how you can use them in vue.

Email Address

Our first example is checking the validity of an email address.  You will notice that there are the methods “hideEmailError”, “submitForm”, and “checkForEmailError”.  There are also the computed value of “showFormError” and the variables “email” and “showEmailError”.  When you click the button, it fires “submitForm”, which checks “showFormError”, which checks “showEmailError”.  Since “showEmailError” is refreshed when on blur, it checks the value when it is provided but doesn’t actually require it.

See the Pen
Using regex to validate inputs: Email Address
by Joe Steinbring (@steinbring)
on CodePen.

Phone Number

For this example, it is much like the one above but instead of using the regex for an email address, it uses the one for a phone number.

See the Pen
Using regex to validate inputs: Phone Number
by Joe Steinbring (@steinbring)
on CodePen.

US ZIP Code

For the final example, you will notice that I specified US zip code and that is because there isn’t a universal regex string for all zip codes.  It’s really different from country to country.

See the Pen
Using regex to validate inputs: US Zip Code
by Joe Steinbring (@steinbring)
on CodePen.

Do you have a favorite regular expression?  Feel free to leave a comment, below.

 

[ Cover Photo by Omar Flores on Unsplash ]

Leave a Reply

Your email address will not be published.