简体   繁体   English

正则表达式 - 数字和特殊符号只允许在输入中

[英]regex -digits and special symbols are only allowed in input

I have 2 input fields in my form (for phone number) and I should validateRe these inputs.我的表单中有 2 个输入字段(用于电话号码),我应该验证这些输入。 Digits 0-9 and ()+- are only allowed and number of digits should be between 5 and 11 only {5,11}.仅允许使用数字 0-9 和 ()+-,并且位数应仅在 5 到 11 之间 {5,11}。 I try to use method replace.我尝试使用方法替换。 Could you explain, how it works?你能解释一下,它是如何工作的吗?

 formPhone.forEach(element => { element.addEventListener("input", (e) => { e.target.value = e.target.value.replace(/[^\d\(\)\+\-]{5,9}/g, ''); }) })

{5,9} quantifier in your code restricts length of a match, but it calculates non-digit symbols ()+- too.代码中的{5,9} 量词限制匹配的长度,但它也计算非数字符号()+- If you want to use regex you can do it in 2 steps:如果您想使用正则表达式,您可以分两步完成:

 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

Please check comments with explanation in the code above.请检查上面代码中的注释和解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM