Regex validation to form

How can I write this so that it outputs to document.getElementById(‘error’) and not console.log. ?


<form onsubmit="validate()">

      <input type="text" id="name" placeholder="name">
     <div id="error"></div>
      <input type="submit">
    </form>

  <script>

    function validate() {

      var name = document.getElementById('name').value;

      var nameRegex = /^[A-Z]+[ ][a-z]?+$/i;

      console.log(nameRegex.test(name));

      return false;
    }

  </script>

Can we see a bit more of the code? It should just be a case of doing something like:

document.getElementById(‘error’).innerText = theErrorMessage

Rather than

console.log(theErrorMessage)

But would need to see how you’ve set it up.

Dont how but what was in script-tag was removed but let me try again.

function validate() {

  var name = document.getElementById('name').value;

  var nameRegex = /^[A-Z]+[ ][a-z]?+$/i;

  console.log(nameRegex.test(name));

  return false;
}

My question is how do I display the result in the “error id”.

Ah sorry! I just realised why it didn’t show - I’ve edited the original post and here’s our standard reply for future reference:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Not this is untested, but I think it works, I would probably do something like:

function validate(e) {
  var name = document.getElementById('name').value;
  var nameRegex = /^[A-Z]+[ ][a-z]?+$/i;

  if (nameRegex.test(name)) {
    // do whatever to just allow submit here 
  } else {
    // Prevent normal functionality -
    // form submit would normally reload the page
    e.preventDefault();
    document.getElementById(‘error’).innerText = "Name is incorrect, please try again.";
  }
}

There are also better ways to do this (and the functionality is built into HTML forms, so you don’t need JS), but something like this should work.