Monday, November 26, 2018

Validation using regular expression in Javascript

Validation is an essential process in any mobile or web applications where we use forms. So I am sharing some ideas on how to do some basic validations ion Javascript using regular expressions. As this is for Javascript, there won't be much changes in other languages also.


Some regular expressions for basic validations.

"/\d/g"             : For matching any digits if present in the string.
            "/\s/g"             : For matching any whitespace character if present in the string.

            "/[a-zA-Z]/g"    : For matching any letters if present in the string.
            "/[0-9]/g"         : For matching any numbers from 0-9 if present in the string.

            "/[abc]/g"         : will check for letters inside the square bracket if present throughout the string.
            "/[a-b]/g"         : will check for items between the range given inside square bracket if present throughout the string.

            "/[a|b]/g"         : will check for any of the items given inside square bracket if present throughout the string.


Test Method

We can use mainly Javascript test() method for pattern checking.

            var pattern = new RegExp("[a-zA-Z]+");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);

this will print true as letters are present inside the string str;

like this for checking digits present inside string, we can perform

            var pattern = new RegExp("/\d/g"); OR var pattern = new RegExp("/[0-9]/g");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);

for checking whitespace present inside string, we can perform

            var pattern = new RegExp("/\s/g");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);



Replace method


If we want to find a pattern in a string and change it with something else, we can use the Javascript replace() method.

If we want to remove all the whitespace characters from the string, we can perform it by

            var pattern = new RegExp("/\s/g");
            var str = "Hello World";
            var res = str.replace(pattern, "");

This will remove all the whitespace characters with empty, like this we can remove any pattern found inside a string, or replace the pattern with some other patterns

0 comments:

Post a Comment