How Can I validate User's Name IF ONLY
- Name has valid characters (NOT Numbers or others symbols)
- Name is NOT equal an empty space
- Name length is bigger than 3 chars
There is a case where I want to accept the value is ONLY if name is NOT entered That's mean that the user want To keep the previous name
I use REACT.js HERE IS MY CODE
const alphabet = /^$|^[a-zA-Z ] $/g;
const numbers = /[0-9]/g;
const isValidNumber = numbers.test(phone)
const isValidName = alphabet.test(name)
if (isValidNumber){
setError(null)
} else{
setError('Please Enter a valid Name');
return
}
if (isValidNumber){
setError(null)
} else{
setError('Please Enter a valid Phone Number');
return
}
CodePudding user response:
I think the below code will help you out.
const alphabet = ^[a-zA-Z ]{4,}$;
if (name.text) {
if (!alphabet.test(this.name.text) ) {
setError('Name must be contain more than 3 characters');
return;
} else {
Do something here
}
} else {
setError('Name cannot be empty');
return;
}
CodePudding user response:
I solved the problem with:
const spaceChar = / {1,}/ ;
const isStartWithSpace = spaceChar.test(name)
if (isValidName){
if (isStartWithSpace){
setError('name Cannot start with a space')
return;
}
setError(null)
} else{
setError('Please Enter a valid Name');
return
}