CancelImage Upload

How to use regular expressions in JavaScript to validate a variable

As you are no doubt aware, JavaScript does things slightly different to other programming languages. In JavaScript then, instead of inserting a regular expression into a bracket, along with the variable to be validated, we actually load the regular expression into a variable, and test the variable to be validated against the regular expression using the function test:

var fourDigitCode = /^([a-zA-Z0-9]{4})$/;

if(fourDigitCode.test(code) == false)
{

       ...

}
else
{

       ...

}


As you can see the above code will either return true or false. Based on this you can define your actions. Here for instance is a text box into which a four digit code should be entered consisting of either numbers or letters. Four digits, no more, and no less. If the criteria is fulfilled the status span below will be set to Success!

<html>
<head>
<title>Regex in JavaScript</title>

<script language="JavaScript">

function validate(code)
{

       var fourDigitCode = /^([a-zA-Z0-9]{4})$/;

       var status = document.getElementById("status");

       if(fourDigitCode.test(code) == false)
       {

              status.innerHTML = "Enter a four digit code.";

       }
       else
       {

              status.innerHTML = "Success!";

       }

}

</script>

<style type="text/css">
<!--

div {
width: 100%;
text-align: center;
margin-top:150px;
}

span {
color: #000099;
font: 8pt verdana;
font-weight:bold;
text-decoration:none;
}

input {
color: #000000;
background: #F8F8F8;
border: 1px solid #353535;
width:250px;
font: 8pt verdana;
font-weight:normal;
text-decoration:none;
margin-top:5px;
}
-->
</style>
</head>
<body>

<div>
<span id="status">Enter a four digit code.</span><br>
<input type="text" name="code" onkeyup="validate(this.value);">
</div>

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com