简体   繁体   中英

Setting custom HTML5 validity message property ignores pattern regex

I'm using the pattern attribute in an HTML5 input. It works fine, until I add a custom message using setCustomValidity. All this is supposed to do is

Sets the validationMessage property of an input element.

But instead my pattern is ignored. If I comment out the setCustomValidity, the pattern works.

HTML

<form>Country code:
    <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
</form>

JS

$('input').get(0).setCustomValidity("It's wrong");

$('input').on('input', function () {
    console.log($(this).prop('validity'));
    var valid = $(this).get(0).checkValidity();
    console.log(valid); });

http://jsfiddle.net/hrtsz50s/

use reportValidity(); insted of checkValidity(); and when you call the function clear the validity with an empty string first!

$('input').get(0).setCustomValidity("It's wrong");

$('input').on('input', function () {
    this.setCustomValidity('');//Add this!!
    console.log($(this).prop('validity'));
    var valid = $(this).get(0).reportValidity();//here
    console.log(valid); });

edit

Got it working in this fiddle: http://jsfiddle.net/hrtsz50s/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM