Javascript code to perform split() on user names entered in input field

I have a field in my HTML form where user is supposed to enter his full names. I need javascript code that can invoke the .split function to ensure there is at least a space between two words entered in the field to validate. The split function should count the number of spaces between words, if it is zero then user has entered a single name word and should show error, if its one and above then user is good as validated. This one busted my nuts wide open, can anyone help me with the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="container">
    <div class="form">
        <label class="accent-1">Enter Your Full Names</label>
        <input type="text" class="form-control" id="mytext">
    </div>
</div>
<script>
    //we are going to scan if user attempted to enter one name using split
    //get the field
    let field=document.getElementById("mytext");
    let y=field.value;
    //javscript split function to fetch substrings into array and check for spaces

</script>
</body>

Answer

You could grab the value and split the string(value) and checks for the length. check accordingly to the condition.

const button = document.querySelector("button");
const input = document.querySelector("input");
const error = document.querySelector("div#error");

button.addEventListener("click", e => {
  const data = input.value.split(" ");
  if (data.length <= 1) {
    error.textContent = "Error";
    // Do when there is only single word - REJECTED CASE
  } else {
    error.textContent = "";
    // Do when there is more than a word - ACCEPTED CASE
  }
})
div#error{
  color: red;
  font-size: 12px;
}
<div class="container">
  <div class="form">
    <label class="accent-1">Enter Your Full Names</label>
    <input type="text" class="form-control" id="mytext">
    <div id="error"></div>
    <button> submit </button>
  </div>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *