RegExp and form validation

RegExp (Regular Expression) are a representation of patterns that match with a characters or text.

Sintaxis:   /pattern/modifiers;

Pattern  is the characters to match and is always inside /.

Modifiers are after the pattern. The different modifiers are:

i   -> case sensitive matching

g  ->global find, find all matching

m  ->multiline matching

Some of the special characters used for the pattern are:

[x-z] brackets used to match a range.

^ match at the begining

$ match at the end

*match 0 or more times

+ match 1 or more times

match  0 or 1 time

matches any single character except the newline character

/d digital character

/D non digital character

/w matches any alphanumeric character including the underscore

/W matches any non-word character

/s matches a single white space character

/S matches a single character other than white space

There are more special character you can use, but for now we will play just with those, you can find more characters and examples on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

Examples:

/\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “50%.”

/\d+?/ matches ‘1’ on “123abc”

/\s\w*/ matches ‘ bar’ in “foo bar.”

But RegExp are not just match or find text, RegExp is used on  html5 Forms on the inputs validation.

The <input> element has a attribute called pattern where you can define the RegExp that will apply to the value on the input.

Input valid password must contain 8 or more characters that are of at least one number, and one uppercase and lowercase letter.

<input type="password" name="pass" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">

Input valid email must contain characters followed by an @ sign, followed by more characters, and then a “.”. After the “.” sign, you can only write 2 to 3 letters from a to z.

<input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">

Pattern attribute can be used on input types: text, date, search, url, tel, email, and password.

Tip: save the common RegExp to use it when you needed.

You can find a useful list here: http://www.labnol.org/internet/regular-expressions-forms/28380/

Leave a comment

Create a website or blog at WordPress.com

Up ↑