0

I'm not sure what's the best way to do this. The form has a single text input but I'm not actually using the form data for anything.

I just need to validate that something has been entered. If it has, the form will then be submitted and a function called.

At this stage I'm just trying to get a basic example working with a bare minimum of code. I was thinking of something along the lines of the following:

HTML

<!DOCTYPE html>
<html>
  <head>
    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous">
    </script>
  </head>
  <body>
    <form name="myForm" onSubmit="return myFunctionName(event)">
      <input id="postcode" name="postcode" required>
      <input type="submit" value="Click Me">
    </form>
  </body>
</html>

jQuery

<script>
var postreg = /^\d{6}$/;
var postcode = document.getElementById("postcode").value;
function myFunctionName(e) {
  e.preventDefault();
  if (postcode.match(postreg)) {
    alert('success');
  } else {
    alert('please enter the correct 6 digit postcode');
  }
 }
 </script>

1 Answer 1

1

Make the field required:

function myFunctionName(e) {
  e.preventDefault(); // just so you can see the below log
  console.log('calling some other function');
}
<form name="myForm" onSubmit="return myFunctionName(event)">
  <input type="text" name="myText" required>
  <input type="submit" value="Click Me">
</form>

To use a regular expression with an input, use the pattern attribute:

function myFunctionName(e) {
  e.preventDefault();
  console.log('submitting...');
}
<form name="myForm" onSubmit="return myFunctionName(event)">
  <input id="postcode" name="postcode" required pattern="\d{6}">
  <input type="submit" value="Click Me">
</form>

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks @Snow. What about if I needed to actually validate the input?
Depends on the type of validation. You might be able to use a regular expression. If not, then you'll have to do it manually. eg document.querySelector('input').value.includes('foo')
Ok, how would I include that in the above example?
I updated my code but still can't get it to work. Any idea what the problem is?
Use the pattern attribute instead
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.