Double Name JavaScript RegEx
I want to only allow one capital letter on startup and another if (after the hyphen), and that you can only write one hyphen so that u can write a double name like Klas-Bertil and nothing else.
Allow:
Klas Klas-Bertil Fredrick-Patrick
not
KlAs- KLaS-bErtIl Fre-Dr-IckP-aTrick
I don't know if I understood it myself? :)
Thanks in advance!
source to share
Have a basic RegEx for parts of the name, like this
var regEx = /^[A-Z][a-z]*$/;
This will match any string that starts with zero or more space characters, followed by an uppercase letter and then a string of small letters, and ends with zero or more characters.
Now split the input line by -
and apply all tags to it regEx
to see if all parts match or not.
var regEx = /^[A-Z][a-z]*$/;
function isInitCapNames(name) {
return name.split("-").every(function(currentPart) {
return regEx.test(currentPart);
});
}
Test cases:
console.assert(isInitCapNames('Klas') === true);
console.assert(isInitCapNames('Klas-Bertil') === true);
console.assert(isInitCapNames('Fredrick-Patrick') === true);
console.assert(isInitCapNames('KlAs-') === false);
console.assert(isInitCapNames('KLaS-bErtIl') === false);
console.assert(isInitCapNames('Fre-Dr-IckP-aTrick') === false);
source to share
How about limiting users by just fixing their input? it would be much more convenient for both sides, I believe:
var names = ["KlAs-","KLaS-bE$@rtIl-banana","Fre-Dr-IckP-aTrick","Klas","Klas-Bertil","Fredrick-Patrick"]
function FixName(name){
//remove all special characters from the name
name = name.replace(/[^a-zA-Z0-9_-]/g,'');
//check for hyphens and only get 1 of those, takes 2 name parts.
var name_parts = name.split('-',2);
//fix the first name part
var Fixed_Name=(name_parts[0].charAt(0).toUpperCase() + name_parts[0].slice(1).toLowerCase()).trim();
//check if there is anything after the hyphen, and fix it too.
if(name_parts[1].trim()!=""){
Fixed_Name+="-"+(name_parts[1].charAt(0).toUpperCase() + name_parts[1].slice(1).toLowerCase()).trim();
}
alert(Fixed_Name);
}
FixName(names[1]);
source to share