Input validation using Regex?

ยท

2 min read

Input validation using Regular Expression

Input Validation ensures that only formatted data is entering the workflow. To ensure this we use some sort of pattern or regex or some logic to let the users know whether the values provided by them meet the specified criteria or not.

We all have looked for a regex pattern(s) to get the work done or explored learning how regex works and struggled with the same!.

This blog is about the common input validation and their Regular Expression. So, Let's start.

1) Regular Expression to check Email validation

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
/^([a-zA-Z0-9_\-.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/

Both the Regular Expression works for most case.

NOTE - there is no perfect Email regex, Hence, make changes to it based on your need

2) Regular Expression to check Password Validation

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*])([a-zA-Z0-9@!*#$%]{8,})*$/

The above regex is for Text must not start and/or end with spaces or Text must contain at least 8 characters that include at least 1 lowercase character, 1 uppercase character, 1 number, and 1 special character.

3) Regular Expression to check input String must not start and/or end with spaces.

/^[^\s]+(\s+[^\s]+)*$/)

4) Regular Expression to check input string must not start and/or end with spaces. and Only letters (a-zA-Z) are allowed.

/^[a-zA-z]+([\s][a-zA-Z]+)*$/

You can check for the resources given below

Also, please feel free to comment if you have something better to share so that, we can learn and grow together.

Thank you for reading... ๐Ÿ™

ย