Introduction:

This article provides a step-by-step guide on how to implement a JavaScript script for validating first and last name input fields in a form. The script ensures that these fields contain only letters, spaces, and for the last names, single quotes.

Implementing the script

Step 1: Firstly, add the following script into the form node where you have first and last name field.

Step 2: Set the script to trigger upon entry.

<script>
  const regexFirstName = /^[a-zA-Z ]*$/; // for first name
  const regexLastName = /^[a-zA-Z' ]*$/; // for last name, includes single quote
  let firstName, lastName, submitBtn, buttonTxt, fn, ln;

  const checkEntry = () => {
    if(!fn || !ln) return; // exits if the elements are not yet defined
    firstName = fn.value;
    lastName = ln.value;
    let invalidFn = !regexFirstName.test(firstName);
    let invalidLn = !regexLastName.test(lastName);
    if (invalidFn || invalidLn) {
      submitBtn.disabled = true;
      submitBtn.innerHTML = 'Name cannot contain special character!';
    } else {
      submitBtn.disabled = false;
      submitBtn.innerHTML = buttonTxt;
    }
  };

  setTimeout(() => {
    submitBtn = document.getElementsByClassName('submit-btn')[0];
    buttonTxt = submitBtn ? submitBtn.innerHTML : "";
    fn = document.getElementsByName('first_name')[0];
    ln = document.getElementsByName('last_name')[0];
    if(fn) fn.addEventListener('keyup', checkEntry);
    if(ln) ln.addEventListener('keyup', checkEntry);
  }, 100);
</script>

Note: The script above uses regular expressions to check the user’s input in the first name and last name fields. This is done each time a key is pressed in either field. If the input does not match the defined format (only letters, spaces, and potentially a single quote for the last name), the submit button is disabled, and its label changes to ‘Name cannot contain special character!’. If the input matches the allowed format, the submit button is enabled, and its label resets to its original text.

Step 3: Test the Functionality

Once the script is implemented, test the form by inputting both valid and invalid address data into the name fields. The form should react as expected, meaning it should prevent the submission of invalid data.

Implementing the steps accurately ensures that your form prohibits special characters in name fields, allowing only spaces and single quotes.