简体   繁体   中英

JavaScript regexp to validate Name with special characters like apostrophe, and spaces

I need to validate names like

Dr. D'souza (valid)
Mr. John (valid)
Doe (valid)

ie allow full stop, space and apostrophe

and inform user when entering invalid special characters like $ * + ?|\\><:;[]{} etc I'm new to regexp. tried altering few but couldn't match

var errmsg = new Array;
var re = /^[a-zA-Z'.,]+({0,1}[a-zA-Z-, ])*$/;

if (!re.test($(this).val())) {
    errmsg.push($(this).attr('placeholder') + ' is invalid');
}

You could use the following regex:

[a-zA-Z]+(?:(?:\. |[' ])[a-zA-Z]+)*

正则表达式可视化

(?:\\. |[' ]) means "either a dot followed by a space, or an apostrophe, or a space". If you need to allow hypens as well for example, replace [' ] by [' -] (a hypen must be either at the beginning or at the end of a class to be matched). More info at http://www.regular-expressions.info/ .

Debuggex Demo

var re = /^[A-Za-z\'\s\.\,]+$/

根据您的要求尝试此正则表达式

试试这个/^\\w(\\w|\\s|['.])*$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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