javascript 只允许字母和空格 - jquery 验证插件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10016693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:28:51  来源:igfitidea点击:

Allow only letters and spaces - jquery validation plugin

javascriptjqueryregexvalidation

提问by user1313360

I am validating a text field to allow only letters and spaces.

我正在验证文本字段以仅允许字母和空格。

This is the method I am using:

这是我正在使用的方法:

jQuery.validator.addMethod("lettersonly", function(value, element) { 
    return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Please enter only letters"); 

But the regular expression is not allowing spaces between words.

但是正则表达式不允许单词之间有空格。

I tried : /^[a-z ]+$/i.test(value)and /^[a-z\s]+$/i.test(value)

我试过: /^[a-z ]+$/i.test(value)/^[a-z\s]+$/i.test(value)

jQuery version - 1.7.1

jQuery 版本 - 1.7.1

回答by gdoron is supporting Monica

The regular expression is:

正则表达式为:

^[a-z\s]*$

LIVE DEMO

现场演示

回答by kishor10d

jQuery.validator.addMethod("lettersonly", function(value, element) { 
    return this.optional(element) || /^[a-zA-Z\s]*$/.test(value);
},"Please enter only letters");

replace this : /^[a-z\s]+$/i

替换这个: /^[a-z\s]+$/i

by this :/^[a-zA-Z\s]*$/

这样 :/^[a-zA-Z\s]*$/

I checked It works.

我检查了它的工作原理。