How to validate a text field so it can only contain a four digit number

前端 未结 2 1328
失恋的感觉
失恋的感觉 2021-01-15 12:03

I\'ve managed to validate my field so it is always four digits, but i need to validate so that it is always a number. I tried adding this block of code but it doesn\'t work

2条回答
  •  Happy的楠姐
    2021-01-15 12:45

    Let's say you get your value here

    var val = document.ExamEntry.cand.value;
    

    Then if you want it to be something with 4 digits inside, just do this

    var itIsNumber = /^\d{4}$/.test(val); // true if it is what you want
    

    if you want it to be something with 1 to 4 digits inside, just do this

    var itIsNumber = /^\d{1,4}$/.test(val); // true if it is what you want
    

    more examples and details here --> Regular Expressions

提交回复
热议问题