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

前端 未结 2 1317
失恋的感觉
失恋的感觉 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条回答
  • 2021-01-15 12:33

    /^[0-9]{4}$/ for four numbers

    /^[0-9]*$/ for any amount of numbers

    /^[0-9]+$/ for at least one number

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题