0
<input type="text" pattern="[a-zA-z]" required id="txtBox" />
<input type="submit" />
  • How do you set "required" attribute from javascript?

  • If I call a javascript event from a submit-type input, how do I check whether that submit request failed due to HTML5 validation errors?

  • Is there a way to force html validation without the submit event happening?

3
  • use .checkValidity() to check if form is valid. Commented Jul 7, 2014 at 9:36
  • 1
    The submit event will not happen if any of the fields invalid. Commented Jul 7, 2014 at 9:37
  • You have to go with either HTML5 or Javascript validation. At which you can 'upgrade' some older browsers to the HTML5 standard with e.g. Modernizr. But mixing the two principle validation methods is asking for trouble in terms of user experience, because two messages will appear every time. After you have made your choice, just do some Googling (there is a ton of info on validation out there) and tell us what it is that you cannot get to work, if any. Commented Jul 7, 2014 at 9:46

2 Answers 2

1
  • document.getElementById('txtBox').required = true;
  • document.getElementById('txtBox').validity.valid is equal to true or false depending on the validity of the element.

There is also invalid event that is fired on invalid form controls.

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

Comments

1

How do you set "required" attribute from javascript?

You can use .prop() method for this:

$('#txtBox').prop('required', true);

If I invoke a click event from javascript on "input" element of type Submit, how do I check if that submit request failed due to HTML5 validation errors?

If you have a html5 required attribute on an input element then if that is not validated properly your form will not be submitted.

Is there a way to force html to check for validations without submit event happening?

Well you can write some function for the element's value check on keyup, keydown events that would do the trick for you then.

something like:

$('#txtBox').prop('required', true);

$('#txtBox').on('keyup', function(){
  var regex = /^[a-zA-z]+$/;
   if(!regex.test(this.value)){
      alert(this.id + ' is a required field.');
   }
});

Comments

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.