将工作英国电话号码JS RegExp转换为HTML模式RegExp

时间:2017-10-11 11:07:27

标签: javascript regex html5 forms validation

我试图让这个英国电话号码的RegExp工作在HTML模式属性中,我可以做基本的RegExp,但这超出了我的范围。

所以模式是(from; Regular expression for UK based and only numeric phone number in cakephp

^(?:(?:\(?(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?(?:\(?0\)?[\s-]?)?)|(?:\(?0))(?:(?:\d{5}\)?[\s-]?\d{4,5})|(?:\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3}))|(?:\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4})|(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}))(?:[\s-]?(?:x|ext\.?|\#)\d{3,4})?$ 

并在控制台中正常工作并返回预期的结果。 INPUT属性中的模式与上面的模式完全匹配,因此到目前为止它不是一个转义问题。

控制台为我提供了上述错误Invalid escape。删除转义的字符会给我Invalid group

进一步阅读问题(invalid escape in pattern HTML/Javascript),我尝试转义],控制台告诉我Invalid character class



input:valid { border-color: green; }
input:invalid { border-color: red; }

RegExp original (Invalid escape);<br/>
<input type="tel" name="mobile" autocomplete="tel" placeholder="Mobile Number" pattern="^(?:(?:\(?(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?(?:\(?0\)?[\s-]?)?)|(?:\(?0))(?:(?:\d{5}\)?[\s-]?\d{4,5})|(?:\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3}))|(?:\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4})|(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}))(?:[\s-]?(?:x|ext\.?|\#)\d{3,4})?$" required="required">
<br/><br/><br/>
RegExp with escaped ] (Invalid character class):<br/>
<input type="tel" name="mobile" autocomplete="tel" placeholder="Mobile Number" pattern="^(?:(?:\(?(?:0(?:0|11)\)?[\s-\]?\(?|\+)44\)?[\s-\]?(?:\(?0\)?[\s-\]?)?)|(?:\(?0))(?:(?:\d{5}\)?[\s-\]?\d{4,5})|(?:\d{4}\)?[\s-\]?(?:\d{5}|\d{3}[\s-\]?\d{3}))|(?:\d{3}\)?[\s-\]?\d{3}[\s-\]?\d{3,4})|(?:\d{2}\)?[\s-\]?\d{4}[\s-\]?\d{4}))(?:[\s-\]?(?:x|ext\.?|\#)\d{3,4})?$" required="required">
<br/><br/><br/>
RegExp with no escaped characters (Invalid group):<br/>
<input type="tel" name="mobile" autocomplete="tel" placeholder="Mobile Number" pattern="^(?:(?:(?(?:0(?:0|11))?[s-]?(?|+)44)?[s-]?(?:(?0)?[s-]?)?)|(?:(?0))(?:(?:d{5})?[s-]?d{4,5})|(?:d{4})?[s-]?(?:d{5}|d{3}[s-]?d{3}))|(?:d{3})?[s-]?d{3}[s-]?d{3,4})|(?:d{2})?[s-]?d{4}[s-]?d{4}))(?:[s-]?(?:x|ext.?|#)d{3,4})?$" required="required">
<br/><br/><br/>
<button onclick="alert(/^(?:(?:\(?(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?(?:\(?0\)?[\s-]?)?)|(?:\(?0))(?:(?:\d{5}\)?[\s-]?\d{4,5})|(?:\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3}))|(?:\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4})|(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}))(?:[\s-]?(?:x|ext\.?|\#)\d{3,4})?$/.test('07904 333 278'))">Test JS</button>
&#13;
&#13;
&#13;

0 个答案:

没有答案