Many developers may face a big problem while dealing with JavaScript; it’s the problem of validating user input using REGULAR EXPRESSIONS

Here are simple steps to do so:

-First what is a regular expression?!

It’s a tool for performing pattern matches and it has to categories

1-literal syntax , it’s something like that

var reg = /pattern/

2-Dynamic regular expression that can be done using the RegExp() constructor , it’s something like that


var reg = new RegExp(“pattern”) ;

after we have got a regular expression we can use it any where

and here’s an example that may be helpful

-In this example we insure that the user enters 6 digits.

first i’ll construct an html form like that

<html>
<head>
<script type=”text/javascript”>
</script>
</head>

<body>
<form name=”iForm”>
<input type=”text” name=”iText” />

<button onclick=”validateInput();”>Click Me</button>

</form>
</body>

</html>

and between the script tags we put our JavaScript code the will get the job done


function validateInput()
{
var reg = /^\d{6}$/
if(document.iForm.iText.value.search(reg)==-1)
{
alert("Wrong input.....Please Enter Valid input !!!!")
}
}

Here i’ll reveal some mysterious about the previous expression

^ this means that it will start comparing from the first digit

d{6}     means that it will do comparing for 6 digits

$     means that it must be 6 digits till the end of the input(actually $ means the end of the input)

here’s another trick if you want to validate email input from the user

w can do this with this function

function validateInput()
{
var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
if(document.iForm.iText.value.search(reg)==-1)
{
alert("Wrong Email.....Please Enter Valid Email !!!!")
}
}

hope you enjoyed this simple tutorial :)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s