Using Regular Expression as validator in JavaScript and PHP ~ Hybrid Mobile Apps Development, React Native, Flutter, JavaScript, Darts, iOS, Android, NodeJS
Coding Savvy FB Twitter Google
» »

Using Regular Expression as validator in JavaScript and PHP

It is the Duty of every developer to validate and make sure that all the data that users supply are valid before it gets to the database, Today I will ensure we touch both sever side and client side validation using the regular expression. "In theoretical computer science and formal language theory, a regular expression (abbreviated regex or regexp and sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. The concept arose in the 1950s, when the American mathematician Stephen Kleene formalized the description of a regular language, and came into common use with the Unix text processing utilities ed, an editor, and grep (global regular expression print), a filter." - Wikipedia.
Using Regular Expression as validator in JavaScript and PHP

Regular expressions are useful in so many cases such as date,phone number,email,special IDs validation e.t.c. it is a powerful pattern-matching tools that allow developers much more control over data than a strict string comparison search.
But before you can start using RegEx for data validation you need to get more comfortable with Regular Expression.
Some people, when confronted with a problem, think, "I know, I’ll use regular expressions." Now they have two problems.Jamie Zawinski
The syntax used in Regular expression is The Perl-Compatible Regular Expression (PCRE) syntax. This syntax is compatible with PHP and JavaScript, as well as most other programming languages.

Perl Compatible Regular Expressions (PCRE) is a regular expression C library inspired by the regular expression capabilities in the Perl programming language, written by Philip Hazel, starting in summer 1997. PCRE's syntax is much more powerful and flexible than either of the POSIX regular expression flavors and many classic regular expression libraries. The name is misleading, because PCRE and Perl each have capabilities not shared by the other. -- Wikipedia

Now let us take a look at the popular delimiters used in Regular Expressions :
\d // Digits.
\w // alphanumeric character letter or number.
\s // White Space .
^ // beginning of a string.
? // Optional .
i //Perform case-insensitive matching.
g //Perform a global match (find all matches rather than stopping after the first match).
m //Perform multiline matching.
$ // End of a string.
\uxxxx // Find the Unicode character specified by the hexadecimal number xxxx (Not supported in JavaScript).
\[0-9] // Digits between 0 to 9.
\[a-z] // Alphabet in lower case between a to z.
\[a-zA-Z] //Alphabet from A to Z in upper and lower case.
\([a-zA-Z][0-9]) // Alphanumeric characters
{2,4} // The minimun expected value is 2 and maximum is 4.
+ //The preceding character or metacharacter must appear one or more times.
(png|jpg) //Matches either "png" or "jpeg".
* // The character or metacharacter can appear one or more times... or not at all. 

Now let get to practice :
//stands for 10 digits
 /^\d\d\d\d\d\d\d\d\d\d$/
 //the expression below also stands for the same thing
 /^\d{10}$/


 <?php
$email = firstname.lastname@aaa.bbb.com;
$regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";

if (preg_match($regexp, $email)) {
    echo "Email address is valid.";
} else {
    echo "Email address is <u>not</u> valid.";
}
?>

RegEx functions
//in PHP
preg_match( pattern, subject [, matches [, flags [, offset]]]);//For matching values
preg_replace( pattern, replacement, subject [, limit ]);//For Replacement of value
//JavaScript
var result = string.replace(pattern, replacement); //For Replacement of value
pattern.test(string); //For matching values

Now for our example: Let create a test for the following IDs:
  • ND/11/EEE/FT/122 or HND/11/EEE/FT/128
First of  on Our client side (JavaScript):
var string1 = "ND/11/eee/FT/122";
var string2 = "HND/11/EEE/FT/122";
var string3 = "HD/11/EEE/FT/122";
var string4 = "nd/15/EEE/FT/122";
var string5 = "ND/15/MEC/FT/122";
var string6 = "ND/15/MEC/pt/003";
var string7 = "HND/15/PS/PT/013";
var pattern =/^((H|P)?ND\/\d{2}\/[A-Za-z]{2}([A-Za-z]{1})?\/(F|P)T\/\d{3})$/ig;

pattern.test(stringn) ? true : false;
//string1 will Return true
//string2 will Return true
//string3 will Return false
//string4 will Return true
//string5 will Return true
//string6 will Return true
//string7 will Return true


On PHP (Server Side) :
$username1 = "nd/11/cec/pt/005";// true
$username2 = "HND/eee/ft/124";// false
$username3 = "nd11eeeft128";// false
$username4 = "hnd/18/eg/ft/03";// false
$username5 = "hnd/18/eg/ft/003";// true
$pattern = '/^((H|P)?ND\/\d{2}\/[A-Za-z]{2}([A-Za-z]{1})?\/(F|P)T\/\d{3})$/ui';
echo preg_match($pattern,$usernamen)? "True":"False";

Here is the list of most common patterns:
'/^[.a-zA-Z_0-9-!@#$%\^&*()]{6,32}$/i #Test for password
 '/^[a-z0-9!#$%&\'*+\/=?^`{}|~_-]+[.a-z0-9!#$%&\'*+\/=?^`{}|~_-]*@[a-z0-9]+[._a-z0-9-]*\.[a-z0-9]+$/i' #email test 
"/^((\d{4})(([\.\/\-])(\d{2})){2})$/i" #date for this formats (2014/03/12,2014.03.16,2086-08-14); 
 "/^((\d{4})(([\.\/\-])(\d{2})){2} (\d{2})(:\d{2}){2})$/i" #date with time, formats (2014/03/12 20:45:32,2014.03.16 20:45:32,2086-08-14 09:45:32);
Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

No comments:

Post a Comment