marcoamorales
marcoamorales

Reputation: 623

Validating Forms in Javascript

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.

Upvotes: 0

Views: 154

Answers (3)

mmorrisson
mmorrisson

Reputation: 541

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 = "";
    }
}

Upvotes: 0

Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24088

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>

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

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 = "";
    }
}

Upvotes: 2

Related Questions