Required Attribute Not work in Safari Browser

Safari, up to version 10.1 from Mar 26, 2017, doesn’t support this attribute, you need to use JavaScript.

This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

HTML:

<form action="" method="post" id="formID">
    <label>Your name: <input required></label><br>
    <label>Your age: <input required></label><br>
    <input type="submit">
</form>

JavaScript:

var form = document.getElementById('formID'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
        if (!event.target.checkValidity()) {
            event.preventDefault(); // dismiss the default functionality
            alert('Please, fill the form'); // error message
        }
    }, false);

You can replace the alert with some kind of less ugly warning, like show a DIV with error message:

document.getElementById('errorMessageDiv').classList.remove("hidden");

and in CSS:

.hidden {
    display: none;
}

and in HTML:

<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>

The only drawback to this approach is it doesn’t handle the exact input that needs to be filled. It would require a loop accross all inputs in the form and checking the value (and better, check for “required” attribute presence).

The loop may look like this:

var elems = form.querySelectorAll("input,textarea,select");
for (var i = 0; i < elems.length; i++) {
    if (elems[i].required && elems[i].value.length === 0) {
        alert('Please, fill the form'); // error message
        break; // show error message only once
    }
}

Leave a Comment