[英]How to validate a first name via regex?
I'm writing a registration page and I need to ask the user for his first name.我正在写一个注册页面,我需要向用户询问他的名字。
I want him to have the option of not capitalizing the first letter but I don't want capital letters inside of his name, and I don't want to allow any non-letter characters as well.我希望他可以选择不将第一个字母大写,但我不想在他的名字中使用大写字母,而且我也不想允许任何非字母字符。
I have written this function for your purpose.我已经为你的目的编写了这个函数。
/**
* This function checks if first name
* is valid. Keep in mind this is
* not the proper solution. It will
* work only for names written in
* latin letters.
* @example
* isFirstNameValid('Ivan')
* will return true.
* isFirstNameValid('IvaN')
* will return false.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions
**/
const isFirstNameValid = (firstName) =>
/^[a-zA-z][a-z]+$/.test(firstName)
Edit: I have implemented a solution with unicode support for the people with a similar problem in the future.编辑:我已经为将来遇到类似问题的人实施了一个支持 unicode 的解决方案。 It supports Latin, Hebrew and Cyrillic.
它支持拉丁文、希伯来文和西里尔文。 If you want to support another cultures you need to provide regexes for them inside cultures hash.
如果你想支持另一种文化,你需要在文化哈希中为它们提供正则表达式。
const isFirstNameValidWithUnicodeSupport = (firstName, culture = 'LATIN') => {
const cultures = {
HEBREW: /^[\u0590-\u05FF]{2,}$/,
CYRILLIC: /^[\u0410-\u042F\u0430-\u044F][\u0430-\u044F]+$/,
LATIN: /^[A-Za-z][a-z]+$/,
};
return cultures[culture].test(firstName);
}
This returns true because is valid name in latin
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('Ivan'));
This returns true because is valid name in cyrillic
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('Иван', 'CYRILLIC'));
This returns false because is valid name in cyrillic
alphabet but there is a space in the end.
console.log(isFirstNameValidWithUnicodeSupport('Иван ', 'CYRILLIC'));
This returns true because is valid name in hebrew
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('אגרת', 'HEBREW'));
This returns false because is valid name in hebrew
but is whole name containing spaces. Not only first name.
console.log(isFirstNameValidWithUnicodeSupport('אגרת בת מחלת', 'HEBREW'));
Edit2: Probably better solution is xregexp library if you want to use library for that purpose. Edit2:如果您想为此目的使用库,可能更好的解决方案是 xregexp 库。 https://github.com/slevithan/xregexp
https://github.com/slevithan/xregexp
You can use regex for matching string characters.您可以使用正则表达式来匹配字符串字符。
let regex = /^[A-Za-z][az]+/g; let name = "Mark"; let match = regex.exec(name); if(match && match[0].length === name.length){ console.log(match[0]); // Mark } else{ console.log("Invalid name"); } name = "mArk"; match = regex.exec(name); if(match && match[0].length === name.length){ console.log(match[0]); } else{ console.log("Invalid name"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.