
[英]I have to write Regex which allowed only @#$% as special symbols and not allow others like ?><`~ symbols
[英]regex -digits and special symbols are only allowed in input
我的表单中有 2 个输入字段(用于电话号码),我应该验证这些输入。 仅允许使用数字 0-9 和 ()+-,并且位数应仅在 5 到 11 之间 {5,11}。 我尝试使用方法替换。 你能解释一下,它是如何工作的吗?
formPhone.forEach(element => { element.addEventListener("input", (e) => { e.target.value = e.target.value.replace(/[^\d\(\)\+\-]{5,9}/g, ''); }) })
代码中的{5,9}
量词限制匹配的长度,但它也计算非数字符号()+-
。 如果您想使用正则表达式,您可以分两步完成:
let phone = '+12(34)567-89-01'; let pureNumbers = phone.replace(/[()+-]/g, ''); // Delete '()+-' symbols from string let isCorrectNumber = /^\d{5,11}$/.test(pureNumbers); // Check if 'pureNumbers' string has only digits and length from 5 to 11 console.log(isCorrectNumber); // true
请检查上面代码中的注释和解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.