开发者

Validating Forms in Javascript

开发者 https://www.devze.com 2022-12-13 01:25 出处:网络
From a question in this site I found the following code of romaintaz: <script type=\"text/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.


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


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>


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

精彩评论

暂无评论...
验证码 换一张
取 消