Search code examples
javascriptvalidationinput

Validation input field Fullname(Firstname,Lastname) - JavaScript


Need validation for full name(first name/last name - 1 input field). I'm new in this sphere and can't formulate the right syntax maybe will work with a regular expression too

<form name="myForm" action="#" id="form" onsubmit="return validateForm()" method="POST">
            <div class="field"><span class="input"><i class="fas fa-user-alt"></i>
                    <input type="text" id="name" name="Fullname" placeholder="Full Name" >
                </span>


function validateForm() {
var name= document.getElementById('name').value;
var x = name.indexOf(" ");
var fname = name.substring(0, x);
var lname = name.substring(x).trim();
if ( 17 < fname.value.length < 5 || 4 > lname.value.length > 17 || x.value.length != 1) {
    alert("try again")
    return false;
 }
 alert("OK")
return true;
}

The field (1 field) should contain 2 words which should be from 3 to 20 symbols.

EDIT:It seems work..finally!

function input (name) {
  let fullNameArr = name.split('')
  const space = ' '
  let firstName = ''
  if (fullNameArr.includes(space)) {
    for (let i = 0; i < fullNameArr.length; i++) {
      if (!firstName.includes(space)) {
        firstName += fullNameArr[i]
      }
    }
  }
  firstName = fullNameArr.splice(0, firstName.length)
  const lastName = fullNameArr
  if (firstName.length > 3 && firstName.length <= 21 && lastName.length >= 3 && lastName.length <= 20 && lastName.includes(space) === false) {
    console.log(firstName)
    console.log(lastName)
  } else {
    console.log('Invalid Name')
    return false
  }
}
input('Todor Markov')


Solution

  • Your model makes several assumptions about names. Having first name and last name as separate input boxes is typically done to remove this barrier.

    From a UX standpoint, if you were not going to have separate fields, you'd need some validation with a tooltip that checked if the user has more than one space that alerts them they must type FirstName LastName.

    From a regex validation view, here's a catch all to ensure it's valid.
    /^[a-z ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.") No numbers, but allow letters and the special characters ,.'-.