[英]HTML form validation for number
I want to enter only 4 digits between 0001
to 9999
then how to I validate?我只想输入
0001
到9999
之间的4 位数字,那么如何验证?
I used [0-9]{4}
but it contains 0000
also.我使用了
[0-9]{4}
但它也包含0000
。
I don't think there is a simple regex for a range between 0001
and 9999
.我认为
0001
和9999
之间的范围没有简单的正则表达式。
^(0{3}[1-9]|0{2}[1-9]\d|0[1-9]\d{2}|[1-9]\d{3})$
My solution is to split expression for each degree.我的解决方案是为每个学位拆分表达式。
0{3}[1-9] = 0001 - 0009
0{2}[1-9]\d = 0010 - 0099
0[1-9]\d{2} = 0100 - 0999
[1-9]\d{3} = 1000 - 9999
You can play with this regex online https://regex101.com/r/TjzoEh/1您可以在线玩这个正则表达式https://regex101.com/r/TjzoEh/1
Use pattern
attribute of text input to validate your regex.使用文本输入的
pattern
属性来验证您的正则表达式。
<input type="text" pattern="^(0{3}[1-9]|0{2}[1-9]\d|0[1-9]\d{2}|[1-9]\d{3})$" title="Four digits code">
Inspired by https://www.regular-expressions.info/numericranges.html灵感来自https://www.regular-expressions.info/numericranges.html
for set your length, you must use maxlength attribute like this:要设置长度,您必须使用 maxlength 属性,如下所示:
<input type="text" maxlength="4"/>
and for check number type, you can use Regular Expressions or Number.isInteger() method.对于支票号码类型,您可以使用正则表达式或Number.isInteger()方法。
For first way, you can use this pattern and find any non-digit in your input对于第一种方式,您可以使用此模式并在输入中找到任何非数字
// Find a non-digit character
let reg = /\D/;
and finally, use it:最后,使用它:
reg.test({{your value}})
For second way, you have to use eval() method in the Number.isInteger() method, for example:对于第二种方式,您必须在Number.isInteger()方法中使用eval()方法,例如:
Number.isInteger(eval({{ your value }}))
NOTE: if you use type="number" attribute in input, use don't have to use regex or any js methods.注意:如果您在输入中使用type="number"属性,则不必使用正则表达式或任何 js 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.