21

I am trying to learn HTML5 and came across the following. I would like to use the pattern input keyword to validate the input as the user types it (e.g. validation after pressing tab or changing focus from input box).

I have tried the following:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" onchange="this.variable.validate()" />  </li>

And as well:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" />  </li>

I made up the code for

onchange="this.variable.validate()" 

How to trigger the validation on value change? I am able to do this only onSubmit.

1
  • 1
    oninput="this.reportValidity()" Commented Nov 26, 2018 at 9:00

8 Answers 8

12
<input type="text" name="country" pattern="[A-z]{3}" oninput="this.reportValidity()" />

Check the oninput bit.

You might want to check older browsers though, something like:

<input type="text" name="country" pattern="[A-z]{3}"
    oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! This should be the top answer. Would be an even better answer if this.reportValidity() was invoked after debounce of the oninput event.
8

Disclaimer:
All I am about to say here works for all modern browsers. The term "modern browser" in this context excludes IE9 and earlier. Also Safari for Windows has only partial support.

If all you need is a styling indicator, you can use pure CSS for this:

input[pattern]:invalid{
  color:red;
}

When using pattern, the onsubmit validation is automatically done by the browser (does not work in Safari for Windows).

3 Comments

The OP requested validation on value change, not on submit.
This is not validation
Can CSS be used to trigger pattern validation only if required is specified ?
6

Use reportValidity()

$('#test').on('input', function (e) {  
    e.target.setCustomValidity('')
if ($(this).val()>3) {
    console.log('o~~~~error');
    this.setCustomValidity('123')
    // this.checkValidity()
   this.reportValidity();
}

then when the #test input is bigger than 3 there is a tips auto pop

   $('#test').on('input', function(e) {
   this.setCustomValidity('')
     if ($(this).val() > 3) {
       this.setCustomValidity('wooo~~~~')
     }
     // e.target.checkValidity()
     this.reportValidity();
   })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input autofocus id='test' type="text" min="1" pattern="[0-9]+" required>
<!--   <button type="submit">submit</button> -->
</form>

https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity

Comments

3

The following jQuery code will force the validation every time the input is changed.

It intercepts the oninput event on the <input...> elements. If the value is invalid after the event, the change is undone and the original value is restored. It handles also situations where the invalid value has been pasted into the field.

The data() function stores and retrieve any data to the element using the HTML5 data-attribute. The function stores the original value into the element data-last-valid.

<script lang="text/javascript">
    // First "input" means event type `oninput`, second "input" is the CSS selector.
    // So read as "for all <input ...> elements set the event handler 
    // for the "oninput" event to the function...
    $(document).on("input", "input", function (event) {
        if (this.checkValidity()) {
            // Store the current valid value for future use
            $(this).data('last-valid', this.value);
        }
        else {
            // Undo the change using the stored last valid value
            this.value = $(this).data('last-valid') || "";
        }
    });
</script>

Comments

1

You should use keyup, focus and blur function to implement your need. For example:

you have input field for password:

<input id="pswd" type="password" required name="pswd" />

In JavaScript Code :

$('input[type=password]').keyup(function() {
// keyup event code here with validation rules });

$('input[type=password]').focus(function() {
// focus code here to show message which contains rules for input field  });

$('input[type=password]').blur(function() {
// blur code here    });

Comments

1

If you would like to use jQuery to backport the pattern functionality to older browsers like IE8, you could do something like:

// Jquery Function to Validate Patterns on Input Objects
(function( $ ){
    $.fn.validatePattern = function(search) {
        // Get the current element's siblings
        var pattern = this.attr('pattern');
        var value = this.val();

        return !(pattern&&(value.length>0)&&!value.match( new RegExp('^'+pattern+'$') ));
    };
})( jQuery );

$(document).ready(function() {
    // Bind pattern checking (invalid) to on change
    $(':input').change(function() {
        if (!$(this).validatePattern()) {
            $(this).addClass('invalidPattern');
        }
    });
    // Bind pattern valid to keyUp
    $(':input').keyUp(function() {
        if ($(this).validatePattern()) {
            $(this).removeClass('invalidPattern');
        }
    });
});

This will add the class invalidPattern to input objects which have a pattern and do not match it. You might also want to add checks for required, etc and on submit checks for the form to prevent submission if patterns don't validate. What I put above is a quick, light script to validate only the pattern.

For a more fully functional shim, look at http://adodson.com/jquery.form.js/

The pattern validation code is from that project.

Comments

1

My suggestion is to prevent the user from entering invalid characters into an input in the first place, so they don't have to go back and correct the form.

<label for="test">Only accepts 'a' characters</label>
<input id="test" type="text"
  placeholder="aa" pattern="[a]{1,2}" maxlength="2"
  oninput="if (!this.checkValidity()) this.value = this.value.slice(0, -1)" /> 

2 Comments

What if I copy paste some text
@zakaiter The original poster wanted to validate input when typed. But to support Copy Paste I believe you could include, onpaste="if (!this.checkValidity()) this.value = this.value.slice(0, -1)"
0

Have you taken a a look at javascript's 'onkey' functions?

onkeyup may be the one you are looking for if you want something as the user types.

In addtion, onchange occurs when the field loses focus, while onkeyup is fired as the user types. Depends on which you need.

You many wanna try something like this:

onchange = variable.validate(this.value)

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.