通过jquery验证表单时,确保字段至少包含一个字母
所以,我非常不擅长正则表达式和 JavaScript。因此,当我意识到我需要通过 jquery 验证表单字段以确保至少使用一个字母字符时,我决定向你们寻求一些帮助。
我想允许用户在此字段中使用撇号、空格、破折号、句点、下划线和字母数字字符。但是,它们必须至少使用一个字母字符。
这是我创建的验证器方法,它可以执行所有操作,但确保至少使用一个 alpha 字符。
$.validator.addMethod("nameRegex", function(value, element) {
return this.optional(element) || /[^a-z/g]+/gi.test(value) || !/[^\.\'\:\-_ a-z0-9]+/gi.test(value);
}, "Name must contain at least one letter.");
有什么建议/提示/见解/侮辱吗?谢谢大家!
So, I suck terribly at regex and javascript. As such, when I realized I needed to validate a form field via jquery to ensure that at least one alpha character was used, I decided to ask you fine folks for some help.
I want to allow user to use apostrophes, spaces, dashes, periods, underscores, and alphanumeric chars in this field. They must, however, use at least one alpha character.
Here is the validator method I created, which does everything but ensure that at least one alpha char is used.
$.validator.addMethod("nameRegex", function(value, element) {
return this.optional(element) || /[^a-z/g]+/gi.test(value) || !/[^\.\'\:\-_ a-z0-9]+/gi.test(value);
}, "Name must contain at least one letter.");
Any tips/hints/insights/insults? Thanks everyone!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很幸运地提前查找了所需的字母,然后仅匹配最小长度的有效字符。在我的示例中,我使用的最小长度为 8 个字符,有效字符包括撇号、空格、连字符、句号、下划线和字母数字字符。我相信 '\w' 字符类应该匹配下划线和字母数字。它似乎在我的测试中有效:
编辑:我添加了一个“?”在前瞻中的“*”之后使量词变得非贪婪。另外我应该指出,我在 Chrome 中对此进行了测试,显然我的测试用例并不是结论性的。我希望这会有所帮助。另一种方法是匹配零到多个有效字符,至少 1 个字母,然后匹配零到多个有效字符。像这样的东西:
I have had luck doing a look ahead for the required letter then matching only on valid characters for the minimum length. In my example I use a minimum length of 8 characters with valid characters of apostrophe, space, hyphen, period, underscore, and alphanumeric characters. The '\w' character class is suppose to match underscore and alphanumerics I believe. It seems to work in my tests:
EDIT: I added a '?' after the '*' in the look ahead to make the quantifier non-greedy. Also I should note that I tested this in Chrome and obviously my test cases are not conclusive. I hope this helps though. Another approach is to match zero to many valid characters, at least 1 letter, then zero to many valid characters. Something like: