pTutorial

New way to learn Programming

JavaScript checking for all numbers

JavaScript: Form validation - checking for all numbers

Often situations arise when web master wanted from the user to put only number like phone number, credit card number zip code or STD code. You can write simple JavaScript function with the help of regular expression for following validation.

Regular Expression for all number

    function checkNumber(data){
        var letters = /^[0-9\s]+$/;
        if (data.match(letters)){
            return true;
        }else{
            return false;
        }
    }

To get only number in text field (0-9) with white space, we use regular expression for this validation (/^[0-9\s]+$/) to allow only numbers in text field. This (^) sign indicate the starting and ($) sign indicate the end point,[0-9\s] means that any number from zero to 9 with space or without space. And plus (+) sign is used to any combination of number.

Checking for all number example JavaScript


<!DOCTYPE html>
<html>
<head>
<script src="http://freeonlinecompiler.ptutorial.com/
js/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#kk').click(function () {
var z = $.trim($('#uk').val());
if (checkNumber(z)) {
$('#kk').css("border-color", "green");
$('#divData').html("You have enter "+" " +z);
$('#uk').css("border-color", "green");
$('#tab').css("border-color", "green");
return false;
} else {
$('#kk').css("border-color", "red");
$('#uk').css("border-color", "red");
$('#divData').html("Enter Numeric Only");
$('#tab').css("border-color", "red");
return false;

}
})
});
function checkNumber(data){
var letters = /^[0-9\s]+$/;
if (data.match(letters)){
return true;
}else{
return false;
}
}
</script>
<style>
table{
border: 1px solid #080808;
margin: 5px;
padding: 10px;
}

</style>
</head>
<body>
<h4>Validation for numbers only</h4>

<table id="tab">
<tr>
</tr>
<tr>
<td>Enter number *</td>
<td> <input type="text" id="uk" name="kk1"></td>
</tr>
<tr>


<td> <input type="submit" id="kk" value="Check"></td>
</tr>
</table>

<div id="divData"></div>
</body>
</html>


Download

Explanation

The match method of string object is used to match the regular expression against the input value of text field.

See Also


QUOTES OF THE DAY

Wicked men obey from fear, good men from love

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER