Home > Back-end >  Validation input full name
Validation input full name

Time:06-25

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

CodePudding user response:

  • 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    "));

CodePudding user response:

You can check if the no. of words are less than equal to two and the length of all the words fall within the specified range.

const message = document.querySelector("small");

document.querySelector("input").addEventListener("keyup", (e) => {
  const isValid = validateInput(e.target.value);
  if (isValid) {
    message.textContent = "Valid input";
  } else {
    message.textContent = "Invalid input";
  }
});

const validateInput = (input) => {
  const words = input.split(" ");
  return words.length <= 2 && words.every((w) => /^[A-Za-z]{3,30}$/.test(w));
};
<div>
  <label>
    Name:
    <input type="text" />
  </label>
</div>
<small>Invalid input</small>

  • Related