1

I want to create custom validity rules for HTML input elements (or polyfill unsupported ones). To blend as well as possible into the browser's native validation procedure, I came up with overwriting the input elements' checkValidity method to hook the logic into:

/* input_element is the DOM element to enhance: */
var original_check = input_element.checkValidity.bind(input_element);

input_element.checkValidity = function() {
    var original_validity = original_check();

    /* run our own check only, if the original check went well */
    if (original_validity && ! custom_validity_checker(input_element)) {
        trigger_event('invalid', input_element);
        return false;
    }

    return original_validity;
};

Are there any problems with this approach, that I didn't anticipate?

As far as I can tell, the solution is robust to being called several times, because the validity checking functions will be stacked and called one after the other.

But could there be other cases, where checkValidity() not being the native method will bite me back?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • 1
    It's very very frowned upon if you're a library author, because if your library ever gets popular you're putting browsers in an awkward position where they don't want to break stuff but also you didn't take part in the proper specification process and yet still "made changes" to native stuff... BUT if it's just for your own website there is no real downside to doing this. It might be unintuitive for future devs who wouldn't expect a "native" function to be doing custom things, but it's also fun and fine and honestly kind of satisfying. – Sheraff Jan 24 '23 at 22:41
  • Too late, sorry! Two months after asking that question I started re-implementing the complete HTML5 validation API in JS: https://hyperform.js.org ;-) To be honest, I mainly did it as compatibility layer to fight the many browser inconsistencies of back then. But fear not! I am old enough to have experienced first-hand the MooTools and prototype.js fiasco so that my implementation tries to play it safe wherever possible. – Boldewyn Jan 25 '23 at 07:41
  • But apart from that: +1! Your comment is spot on! – Boldewyn Jan 25 '23 at 07:42
  • Ah ah definitely didn't check the date before commenting! – Sheraff Jan 25 '23 at 20:52

0 Answers0