开发者

Restrict numbers and limit them to two

How to restrict my text field to numbers only and limit them in two开发者_如何学JAVA with a single function.


Since no one has suggested a regular expression, I will. :-)

var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
  // number is one or two digits with optional leading minus
} else {
  // it's not
}


For limiting them to enter only 2 char use maxlength attribute of input. To check enter string is number or not user isNaN(str) function.


<script type="text/javascript">
    function ValidateField(FieldName){

        // Get fields value
        var FieldVal = document.GetElementById(FieldName).value;

        // Check it's a number, and then check it's range is correct
        // Alternatively you could do FieldVal.length
        if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
            alert("Valid!");
        else
            alert("Invalid");
    }
</script>    

<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>

I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.


In HTML5 you can just use: <input type="number" />


If you are using jquery:

$('#myTextAreaID').keydown(function(event) {
  if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
     event.preventDefault();
   }
});

if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜