views:

42

answers:

3

From a question in this site I found the following code of romaintaz:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

My question now is: How can I make this validator only accept numbers and nothing else? Any integer.

+2  A: 

You can chance your regular expression to accept only numeric digits (only integer numbers):

function testField(field) {
    var regExpr = /^[0-9]+$/;
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}
CMS
Thank you, works perfectly :)
dohkoxar
You're welcome @dohkoxar, BTW if you need to check negative integers, just add an optional `-` character to the RegExp: `/^-?[0-9]+$/`
CMS
A: 

This will accept positive and negative integer number with not more than 17 digits.

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^-?\d{1,17}$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>
Dmytrii Nagirniak
A: 

To allow the possibly of signed integers:

function testField(field) {
    var regExpr = new RegExp("^(\+|-)?\d+$");
    if (!regExpr.test(field.value)) {
      // Not a number
      field.value = "";
    }
}
mmorrisson