Ask Your Question
0

What is the method for creating a javascript string that permits the entry of only first and last names in a text field box of a contact form?

asked 2023-07-01 00:41:13 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-01 00:52:01 +0000

lalupa gravatar image

You can create a javascript function that validates the input of the text field box, allowing only letters and spaces for the first and last name. Here is an example:

function validateName(inputText) {
  var nameFormat = /^[a-zA-Z\s]+$/;
  return nameFormat.test(inputText);
}

Then, you can use this function to check the input from the text field box and provide feedback to the user. For example:

var nameInput = document.getElementById("name");
var feedback = document.getElementById("feedback");

nameInput.addEventListener("blur", function() {
  if (!validateName(nameInput.value)) {
    feedback.innerHTML = "Please enter a valid first and last name";
    nameInput.classList.add("invalid");
  } else {
    feedback.innerHTML = "";
    nameInput.classList.remove("invalid");
  }
});

In this code, the validateName function checks if the input matches the regular expression for first and last names. If it doesn't match, the feedback element displays an error message and the invalid class is added to the nameInput element to highlight it. If it does match, the error message is cleared and the invalid class is removed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-01 00:41:13 +0000

Seen: 20 times

Last updated: Jul 01 '23