Number Validation in JavaScript

Sometimes, you may get business requirement where you need to allows users to enter only numbers, we can do JavaScript number validation very easily.

<html>
<body>
<script type='text/javascript'>
function onlyNumberValidation()
{
var numbers = /^[0-9]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter numbers only.");
return true;
}
else
{
alert('Only numbers are allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="onlyNumberValidation()" value='Submit' />
</form>
</body>
</html>

Sometimes, you may get business requirement where you need to allows users to enter either letter and numbers, we can validate letters and numbers by using JavaScript very easily.


<html>
<body>
<script type='text/javascript'>
function letterAndNumberValidation()
{
var letterAndNumberValue = /^[0-9a-zA-Z]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter letters or numbers only.");
return true;
}
else
{
alert('Only letters and numbers allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="letterAndNumberValidation()" value='Submit' />
</form>
</body>
</html>

Leave a Reply

Your email address will not be published.