Validation in HTML5. :invalid classe after submit

2020-08-09 06:25发布

I'm building a form and I want to use the :invalid selector to give the "required" input fields a red border if the user presses submit without filling them, but using this makes them appear highlighted right when the page loads. It seems unfriendly to give this kind of warning to the user before even giving him the chance to fill them at least once.

Is there a way that these fields appear highlighted only after trying to submit the form, said in another way, is there a way to run the validation only after clicking submit (or at least losing focus on the required input fields?)

标签: forms html css
8条回答
2楼-- · 2020-08-09 07:01

In addition to @Alexander Farkas' post, Dave Rupert has a very workable solution here: Happier HTML5 Form Validation.

Essentially, what it does is add a CSS class to form input elements that only displays after a user attempts to submit the form. This is much better UX, in that these elements won't show the invalid styling by default, or when a user tabs through them, which enhances accessibility.

Prior to finding this, I tried styling elements with :invalid:focus and other pseudo-elements, but didn't get the desired effect. Although I try to do my styling with pure CSS as much as possible, this looks like a use case where efficient JS is the practical solution.

查看更多
做个烂人
3楼-- · 2020-08-09 07:03

for 'required' validation

way 1 - set 'required' attribute for each element on form submit

// submit button event
$('#form-submit-btn').click(function(event) {
    // set required attribute for each element
    $('#elm1, #elm2').attr('required','true');

    // since required attribute were not set (before this event), prevent form submission
    if(!$('#form')[0].checkValidity())
        return;

    // submit form if form is valid
    $('#form').submit();

});

way 2 - use 'data' attribute

<input type="text" data-required="1">

<script type="text/javascript">
// submit button event
$('#form-submit-btn').click(function(event) {
    // set required attribute based on data attribute
    $(':input[data-required]').attr('required','true');

    // since required attribute were not set (before this event), prevent form submission
    if(!$('#form')[0].checkValidity())
        return;

    // submit form if form is valid
    $('#form').submit();

});
</script>
查看更多
登录 后发表回答