0

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.

3 Answers 3

2

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 = "";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome @dohkoxar, BTW if you need to check negative integers, just add an optional - character to the RegExp: /^-?[0-9]+$/
0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.