2

I am using the following script to change the HTML5 required attribute of my input elements. I am wonder whether there is a way to modify this script to make it also work in Safari browsers, since Safari does not support this attribute.

Here is the script:

$(document).ready(function() {
    $_POST = array();
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("This field can't be blank");

            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");

        };
    }
})
SheetJS
  • 22,470
  • 12
  • 65
  • 75
John Siniger
  • 875
  • 2
  • 16
  • 39
  • What's this `$_POST = array()`? Doesn't look right... – elclanrs Oct 27 '13 at 02:11
  • This is working for another purpouse, doesn't have anything to do with the whole. I will remove it from the question. – John Siniger Oct 27 '13 at 02:13
  • Possible duplicate of [Safari is not acknowledging the "required" attribute. How to fix it?](http://stackoverflow.com/questions/32684657/safari-is-not-acknowledging-the-required-attribute-how-to-fix-it) – Tommy Feb 24 '16 at 11:33

3 Answers3

4

You can also do this:

var valid = true;
$('input[required]').each(function() {
    if (this.value == '') {
        // Alert or message to let them know
        valid = false;
        return false; // stop on first error, or remove this and it'll go through all of them.
    }
});

if (valid === false) {
    return false;
}
arleslie
  • 460
  • 1
  • 4
  • 16
2

Check out this page here. It contains a hacky solution that should add the desired functionality

http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

Machavity
  • 30,841
  • 27
  • 92
  • 100
0

You're going to need to run the check yourself using an event handler on your form submission. In that handler, you run the check yourself, and if it fails, you display whatever error message and block the submission using preventDefault or return false.

An example can be found here, though as it notes, you need to be careful if you use checkValidity as your means of checking the form.

Evan
  • 825
  • 4
  • 14