简体   繁体   中英

Extending the HTML 5/JavaScript input validation API

I'm to work with with the HTML 5 validation on an input type number field, that uses min and step attributes, and an initial value, ie,

<input type="number" min="50" step="50" value="100" />

However, I want the validation to allow the user to enter values that are greater than the min, but between the steps, here shown in bold:

50, 51 ... 99 , 100, 101 ... 149 , 150, 151 ...

Can I somehow 'hook' into the validation API after it has performed its work, and if the only error that it finds is a step error, reset the valid condition so that the form that it the field is in can be submitted?

Sure would be nice if besides a message string parameter, the element.setCustomValidity() function could also accept a callback function that returned a empty string if the element's value passed the check(s) in the callback function or return a non-empty message string if the value didn't pass.

You can work with a text input and use a pattern attribute that uses a Regular Expression (RegExp) to validate its values like so:

<form>
    <input type="text" pattern="(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)" title="Invalid values" required>
</form>

Edit 1: Since you don't want to change the input type this may be the solution (using the same RegEx):

<script>
    window.validate50 = function(ev){
        var tar = ev.target || ev;

        // tests the value is not a 50 multiple
        if(!/(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)/img.test(tar.value)){

            // in this case triggers the validation using the text on html title attribute
            tar.setCustomValidity(tar.title);

            // returns false so the "submit" action is supressed
            return false;
        }
    };
</script>
<form>
    <input type="number" min="50" step="50" onchange="return validate50(this);" title="The number must not be a multiple of 50!" required>
</form>

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