Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validation input full name

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 :
      ''
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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    "));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading