Required attribute HTML5
Asked Answered
A

7

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?

Abet answered 9/6, 2010 at 9:50 Comment(4)
Now no need to set the required attribute to true. For example: <input type="text" id="name" required="true" /> and <input type="text" id="name" required /> is the sameHasdrubal
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...Overshine
What is the actual and expected behavior?Patrilineage
according to 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 requiredGolda
G
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.

Gonna answered 14/6, 2010 at 19:46 Comment(3)
You can also use novalidate on the form tag to do this for the entire form.Muirhead
I have packaged a small Chrome extension adding this attribute to all the forms in the current tab, thanks for the tip! chrome.google.com/webstore/detail/html5-form-validation-rem/…Cadi
Was important for my case, formnovalidate works with button type submit too: <button type="submit" formnovalidate>Submit</button>.Elba
S
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.

Subcontinent answered 10/6, 2010 at 8:59 Comment(7)
This answer is true, but I think that isn't the problem that we have here.Ojeda
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...Cohesive
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).Cleodell
@RyanWheale I think client side validation (while insufficient by itself) really matters tooCq
@Cq - 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).Cleodell
Or required="ReQuIrEd".Patrilineage
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?Mcspadden
G
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.

Gonna answered 14/6, 2010 at 19:46 Comment(3)
You can also use novalidate on the form tag to do this for the entire form.Muirhead
I have packaged a small Chrome extension adding this attribute to all the forms in the current tab, thanks for the tip! chrome.google.com/webstore/detail/html5-form-validation-rem/…Cadi
Was important for my case, formnovalidate works with button type submit too: <button type="submit" formnovalidate>Submit</button>.Elba
M
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

Metonymy answered 9/6, 2010 at 9:58 Comment(3)
And that is why we shouldn't make up custom attributes or properties on standard objects.Salado
Any ideas how to turn off this for Chrome and Safari for the particular page?Toandfro
@Toandfro go to about:flags to disable this in Chrome. Firefox, I'm not sure.Spivey
C
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;
    }
}
Cita answered 29/7, 2014 at 7:47 Comment(2)
Is that plain CSS or Less?Lethbridge
I have an iPod touch that for the life of me, still fires up when inputs marked as required didn't work and found this Q&A. This answer was the only one that worked for me. Just thought I'd share that.Layoff
C
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".

Caldwell answered 17/11, 2010 at 13:9 Comment(2)
And these work fine in older browsers (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).Mafala
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.Spivey
A
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.

Abet answered 9/6, 2010 at 9:57 Comment(3)
Damn, you answered your own question within seconds of me posting the same answer!Metonymy
Thanks to one of my colleagues indeed. This can be interesting for others I suppose?Abet
Definitely! I'm kind of excited to see what the final HTML5 spec will have to offer on the form front.Metonymy
C
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>
Cabstand answered 1/7, 2015 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.