简体   繁体   English

正则表达式:JQuery检查

[英]Regular expressions: JQuery check

I am working on a form text input that requires the user to enter an "a" followed by 6 proceeding numbers (0-9). 我正在处理一个表单文本输入,要求用户输入一个“ a”,后跟6个连续数字(0-9)。

 (a|)\\d{6} 

The JS does not allow the user to type in anything other than a string in this format. JS不允许用户以这种格式输入除字符串以外的任何内容。

However, I am having no luck. 但是,我没有运气。 The example of my code is located here 我的代码示例位于此处

It is a very bad idea to stop the user from typing anything they want. 阻止用户键入他们想要的任何内容是一个非常糟糕的主意。 Here's why: 原因如下:

Let's say I miss the key I intended to press, and end up entering this sequence of keystrokes: 假设我错过了要按的键,并最终输入了以下击键序列:

a 1 2 3 r Backspace 4 5 6 a 1 2 3 r 退格键 4 5 6

I would expect that my slip would have been erased by my backspace, and the rest of the input went through. 我希望我的支票会被退格键删除,其余的输入都会通过。 Imagine how surprised I'd be to see "a12456" in there instead, because your code had already stopped me from typing r , which means that my Backspace erased the 3 ! 想象一下,如果我在那里看到“ a12456”会多么惊讶,因为您的代码已经阻止我键入r ,这意味着我的Backspace删除了3

Instead, try this: 相反,请尝试以下操作:

<input type="text" name="code" pattern="a[0-9]{6}" required
               title="Please enter an &quot;a&quot; followed by six digits." />

Demo on JSFiddle JSFiddle上的演示

This feature of HTML5 will prevent the form from being submitted if the user does not enter data in the correct format. 如果用户未以正确的格式输入数据,HTML5的此功能将阻止提交表单。 This, combined with server-side confirmation, will work beautifully. 结合服务器端确认,可以很好地工作。 Plus, it even works if the user has JavaScript disabled! 另外,即使用户禁用了JavaScript,它也可以正常工作!

That said, for such a specific format, it may be more helpful to do this: 也就是说,对于这种特定格式,这样做可能会更有用:

a<input type="text" name="code" pattern="[0-9]{6}" required
                                     title="Please enter six digits" />

Demo on JSFiddle JSFiddle上的演示

In this way, the "a" is already there and doesn't have to be typed, leaving the user to only need to type the part that changes. 这样,“ a”已经存在并且不必键入,从而使用户只需要键入更改的部分。 On the server, just stick the "a" back on to it. 在服务器上,只需将“ a”粘贴回去即可。

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

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