我想应用验证,即用户可以写入字符串,但不能以最多 5 位数字的连续模式输入电子邮件 ID 和数字。我正在尝试以下不起作用:
^[a-zA-Z][0-9]{0,5}$
就像用户写:
- 你好 12345 很好 ---> 真的,
- 你好134566不好---->假,
- 你好 +32444 不好--->假, 你好13233很好
- ,我有12333--->真的
提前致谢
这应该适合您:
^[A-z ,]*(([0-9]s?){1,5})([A-z ,]*)(([A-z ,]+)(([0-9]s?){1,5}))*$
解释:
-
^
匹配字符串的开头 -
[A-z ,]*
匹配数字之前的文本 -
(([0-9]s?){1,5})
匹配带有空格的数字 -
([A-z ,]*)
匹配第一个数字后面的文本 -
([A-z ,]+)(([0-9]s?){1,5})
匹配所有其他带有空格的数字,如果数字之间的文本 -
$
匹配字符串的末尾
https://regex101.com/r/EbKsZG/2/tests
我使用以下正则表达式作为解决方案:
^([a-zA-Z,s]+[0-9s]{0,5})+$
有时人们输入带有空格的数字,特别是电话号码来限制他们,我在Keyup
事件中使用功能:
valid(){
this.commmentValid=false; //condition to show or not on html page
var count=0;
// Remove space from starting and end of string
var a = (this.commentData.comment).trim();
// Split each string value and form an array
var m = a.split("");
var preVal;
// console.log(m)
m.forEach(el => {
console.log(el);
var d= el.match(/d+/);
//Check if value is digit
if(d){
//Store previous value
preVal=el;
count++;
if(count>=6){
// Run when find phone number with and without space
this.commmentValid=true;
}
}
//If find space
else if(el == " "){
if(preVal){
count++;
}
}
//Check if string is ok
else{
count =0;
preVal=0;
}
});
}