Introduction
When you need to validate your users input in an HTML form, we all usually use JavaScript which is faster and light weight. But have you ever thought of how to include regular expression to validate input with JavaScript? Well here is a comprehensive example just for that. You can use RegExp object to achieve this objective.
Using the code
For this example let's say for a certain field we need to limit the user from entering special characters.
Following is the basic HTML code for the page.
<!DOCTYPE html>
<html>
<head>
<title>JS and RegEx</title>
</head>
<body>
<label for="txtUsername">Username</lable>
<input type="text" id="txtUsername" placeholder="Enter Username"/>
</body>
</html>
In this particular page it will allow the user to enter anything as the username. But our requirement is to limit the user from entering special characters.
function ValidateInput(evt)
{
var valRegExp = new RegExp("^[a-zA-Z0-9]");
if (valRegExp.test(String.fromCharCode(evt.which)))
{
return true;
}
else
{
return false;
}
}
Now you can see here in this function we have used valRegExp
of type RegExp
which allows us to create the regular expression. And we call the test
method in valRegExp
object to check if the entered character is allowed. String.fromCharCode
method returns the character of the given ASCII code.
Full code is as follows.
<!DOCTYPE html>
<pre> <html>
<head>
<title>JS and RegEx</title>
<script type="text/javascript">
function ValidateInput(evt)
{
var valRegExp = new RegExp("^[a-zA-Z0-9]");
if (valRegExp.test(String.fromCharCode(evt.which)))
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<label for="txtUsername">Username</lable>
<input type="text" id="txtUsername" placeholder="Enter Username" onkeypress="return ValidateInput(event)"/>
</body>
</html>
Hope this helps.