正则表达式:JQuery检查 [英] Regular expressions: JQuery check

查看:56
本文介绍了正则表达式:JQuery检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个表单文本输入,要求用户输入一个"a",后跟6个继续输入的数字(0-9).

I am working on a form text input that requires the user to enter an "a" followed by 6 proceeding numbers (0-9).

(a|)\d{6}

JS不允许用户以这种格式输入除字符串以外的任何内容.

The JS does not allow the user to type in anything other than a string in this format.

但是,我没有运气. 我的代码示例是位于此处

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 退格 4 5 6

a123rBackspace456

我希望我的支票会被退格键删除,其余的输入会通过.想象一下,我在那里看到"a12456"是多么惊讶,因为您的代码已经阻止我键入 r ,这意味着我的 Backspace 删除了

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!

相反,请尝试以下操作:

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." />

JSFiddle上的演示

如果用户未以正确的格式输入数据,HTML5的此功能将阻止提交表单.结合服务器端确认,可以很好地工作.另外,即使用户禁用了JavaScript,它也可以正常工作!

This feature of HTML5 will prevent the form from being submitted if the user does not enter data in the correct format. This, combined with server-side confirmation, will work beautifully. Plus, it even works if the user has JavaScript disabled!

也就是说,对于这种特定格式,这样做可能会更有用:

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" />

JSFiddle上的演示

通过这种方式,"a"已经存在并且不必键入,从而使用户只需要键入更改的部分.在服务器上,只需将"a"粘贴回去即可.

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. On the server, just stick the "a" back on to it.

这篇关于正则表达式:JQuery检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆