80

Within my web application I am using some custom validation for my form fields. Within the same form I have two buttons: one to actually submit the form and the other to cancel/reset the form.

Mostly I use Safari as my default browser. Now Safari 5 is out and suddenly my cancel/reset button didn't work anymore. Every time I did hit the reset button the first field in my form did get the focus. However this is the same behavior as my custom form validation. When trying it with another browser everything just worked fine. I had to be a Safari 5 problem.

I changed a bit in my Javascript code and I found out that the following line was causing the problem:

document.getElementById("somefield").required = true;

To be sure that would be really the problem I created a test scenario:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>

<body>
    <form id="someform">
        <label>Name:</label>&nbsp;<input type="text" id="name" required="true" /><br/>
        <label>Car:</label>&nbsp;<input type="text" id="car" required="true" /><br/>
        <br/>
        <input type="submit" id="btnsubmit" value="Submit!" />
    </form>
</body>
</html>

What I expected would happen did happen. The first field "name" did get the focus automatically.

Anyone else stumbled into this?

Trott
  • 66,479
  • 23
  • 173
  • 212
Joop
  • 2,819
  • 2
  • 20
  • 26
  • 2
    Now no need to set the required attribute to true. For example: and is the same – R.S.K Mar 03 '14 at 04:26
  • True, it's a bad habit from mine, when I was used to code in XHTML... But do all the modern browsers support this tag without ="required" ? I believe that Safari does not... – Loic Cara Sep 29 '14 at 15:52
  • What is the actual and expected behavior? – Ciro Santilli OurBigBook.com Jun 02 '16 at 08:39
  • according to http://blog.grayghostvisuals.com/html/using-html-required-attribute/ "If the attribute is present, its value must either be the empty string or a value that is a case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace." for the "boolean" attributes, so instead of required="true" should have required="required" or just required – George Birbilis Mar 31 '18 at 11:49

7 Answers7

255

Note that

<input type="text" id="car" required="true" />

is wrong, it should be one of

<input type="text" id="car" required />
<input type="text" id="car" required="" />
<input type="text" id="car" required='' />
<input type="text" id="car" required=required />
<input type="text" id="car" required="required" />
<input type="text" id="car" required='required' />

This is because the true value suggests that the false value will make the form control optional, which is not the case.

Ms2ger
  • 15,596
  • 6
  • 36
  • 35
  • 7
    This answer is true, but I think that isn't the problem that we have here. – PhoneixS Aug 16 '12 at 11:53
  • is this safe to use ? ... I mean should I use this or just stick to javascript validation ? by safe I mean , do this solution produce anomalies on different browser/device... – Kevin Florenz Daus Mar 19 '13 at 06:21
  • 8
    I would like to point out that the original code is not "wrong", it just implies that you could use `false` in order to make a field optional (not required) - which is not the case. The thing you must understand is that the presence of the `required` attribute makes the field required. The only way to make the field optional is to remove the attribute. And SERVER SIDE VALIDATION IS ALL THAT REALLY MATTERS (sorry for screaming). – Ryan Wheale Jul 18 '13 at 14:04
  • @RyanWheale I think client side validation (while insufficient by itself) really matters too – jinglesthula Dec 09 '13 at 22:08
  • 1
    @jinglesthula - Client-side validation is nothing but a convenience for the user (saving round trips to the server, resulting in better UX). I was addressing a previous comment *"is this safe to use [across browsers]"* - and the answer is that it doesn't really matter so long as your server-side validation is working (eg. older browser won't recognize HTML5 form validation and will submit a "required" field with a null value). – Ryan Wheale Dec 09 '13 at 23:32
  • Or `required="ReQuIrEd"`. – Ciro Santilli OurBigBook.com Jun 02 '16 at 08:40
  • What if the user right clicks -> Inspect Element, remove the 'required' attribute and then try to submit the form with an empty input. The backend will now receive an empty field. Is there a way to prevent the user from tampering the 'required' attribute in the frontend? – Kemat Rochi May 16 '19 at 03:39
48

I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:

http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate

<input type=submit formnovalidate name=cancel value="Cancel">

Works on Safari 5 and Opera 10.

Darrik Spaude
  • 512
  • 4
  • 2
  • 8
    You can also use `novalidate` on the form tag to do this for the entire form. – Michael Mior Jun 09 '11 at 13:53
  • I have packaged a small Chrome extension adding this attribute to all the forms in the current tab, thanks for the tip! https://chrome.google.com/webstore/detail/html5-form-validation-rem/dcpagcgkpeflhhampddilklcnjdjlmlb – Damien Apr 10 '13 at 14:17
  • Was important for my case, `formnovalidate` works with button type submit too: ``. – Mayeenul Islam Aug 16 '18 at 07:03
19

If I understand your question correctly, is it the fact that the required attribute appears to have default behaviour in Safari that's confusing you? If so, see: http://w3c.github.io/html/sec-forms.html#the-required-attribute

required is not a custom attribute in HTML 5. It's defined in the spec, and is used in precisely the way you're presently using it.

EDIT: Well, not precisely. As ms2ger has pointed out, the required attribute is a boolean attribute, and here's what the HTML 5 spec has to say about those:

Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

See: http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes

Md_Zubair Ahmed
  • 165
  • 2
  • 12
David Foster
  • 3,824
  • 4
  • 25
  • 28
8

Safari 7.0.5 still does not support notification for validation of input fields.

To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA

To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation

function hasHtml5Validation () {
  //Check if validation supported && not safari
  return (typeof document.createElement('input').checkValidity === 'function') && 
    !(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}

$('form').submit(function(){
    if(!hasHtml5Validation())
    {
        var isValid = true;
        var $inputs = $(this).find('[required]');
        $inputs.each(function(){
            var $input = $(this);
            $input.removeClass('invalid');
            if(!$.trim($input.val()).length)
            {
                isValid = false;
                $input.addClass('invalid');                 
            }
        });
        if(!isValid)
        {
            return false;
        }
    }
});

SASS / LESS:

input, select, textarea {
    @include appearance(none);
    border-radius: 0px;

    &.invalid {
        border-color: red !important;
    }
}
Evalds Urtans
  • 6,436
  • 1
  • 41
  • 31
7

A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-, i.e. data-my-attribute="true".

Ludder
  • 2,665
  • 1
  • 25
  • 26
  • 1
    And [these work fine in older browsers](http://stackoverflow.com/questions/2412947/do-html5-custom-data-attributes-work-in-ie-6) (except you’ll need your own code to access their values, rather than the new API), so they’re a better choice than making up your own attributes (as they won’t clash with any official attributes added in the future). – Paul D. Waite Jul 09 '11 at 10:44
  • 1
    Actually, custom attributes can literally be anything. Those prefixed with "data-" will appear in the `element.dataset` object, however, as well as other advantages (for instance, jQuery will automatically be able to grab the value of any "data-" prefixed custom attribute using the `.data()` method, i.e. `.data("myAttribute")` = value of `data-my-attribute`). Using shorter custom attributes can sometimes be useful for making custom CSS3 selectors. – therealklanni Oct 20 '11 at 01:29
3

Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute

Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.

Joop
  • 2,819
  • 2
  • 20
  • 26
2

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>
emotality
  • 12,795
  • 4
  • 39
  • 60