I am using formik with react And i have a signup page where i need to have the following
- No special characters
- Name should not start with space or end with space
- First letter should always be capital letter Eg Abhi Kumar Abhishek Ray
Etc
So what validation should i place I am using only name field and i want to place it in single text field
So can anyone help
CodePudding user response:
Here is functional code with test strings:
const names = [
// match:
'Single',
'First Last',
'Frank O',
'Mike McIntosh',
'Eg Abhi Kumar Abhishek Ray',
// no match:
'Anne-Marie Smith',
"O'Brian",
'Müller',
'山本',
' Space At Start',
'Space At End ',
];
const re = /^[A-Z][A-Za-z]*( [A-Z][A-Za-z]*)*$/;
names.forEach(name => {
console.log(name ' => ' re.test(name));
});
Output:
Single => true
First Last => true
Frank O => true
Mike McIntosh => true
Eg Abhi Kumar Abhishek Ray => true
Anne-Marie Smith => false
O'Brian => false
Müller => false
山本 => false
Space At Start => false
Space At End => false
Explanation:
^
- anchor at beginning[A-Z]
- expect one uppercase char[A-Za-z]*
- followed by optional upper & lowercase chars(
...)*
- optional pattern (0 to multiple instances) of:[A-Z]
- one uppercase char[A-Za-z]*
- optional upper & lowercase chars
$
- anchor at end- if you want to support
O'Brian
andAnne-Marie
, add'
and-
to the pattern, e.g.[A-Za-z'-]*
CodePudding user response:
Here is the one which may help you :
reg = new RegExp(/^[A-Z][a-zA-Z]{1,19}$/)
console.log(reg.test("Sachin"))
console.log(reg.test("sachin"))
console.log(reg.test(""))
console.log(reg.test("Sach-in"))
I hope this answer helps you!
Comment if you have any questions or doubts and don't forget to mark the answer as accepted if you find it useful because it'll be helpful for others who're looking for the answer to the same question.
Have a great day!