There is a task: The field “First Name Last Name” can only consist of 2 words (first name and last name). Min length of each word is 3 characters, max 30. There is only 1 space between words.
The problem is that after the first word, when you put a space, it already returns true. Why? And how to check the 1 space in this input?
const validateInput = (value) => {
const lengthValue = value.split(' ').length
if (lengthValue !== 2) {
return false
} else {
return value.split(' ').filter(el => el.length > 3 && el.length <= 30) ?
value.search(/[A-Za-z]+(\s+[A-Za-z]+)?/gi) !== -1 ?
true :
false :
''
}
}
>Solution :
- Use trim to remove spaces from around the words before testing
- No need for else after a return. Makes it easier to read too
- Why are you testing the words in the name for whitespace? That only works if the user pasted a newline or a tab, since you split on space
- You have a nested ternary, why would you return an empty string there?
Also please read this for the future falsehoods programmers believe about names
const re = /[A-Za-z]{3,30}/;
const validateInput = (value) => {
const val = value.trim();
if (val === "") return false;
const arr = value.split(' ');
if (arr.length != 2) return false;
const [firstName, lastName] = arr;
return re.test(firstName) && re.test(lastName); // we could use .every here but you only have two
}
console.log(validateInput("Hans Anders"));
console.log(validateInput("Prince"));
console.log(validateInput("X Æ A-12"));
console.log(validateInput(" A "));