Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input:invalid css rule is applied on page load

Check out these two fiddles in Firefox or Chrome. In this one, I've got just a simple form with a required attribute and a submit button. Pressing "submit" when the box is empty causes it to be styled as invalid (in Firefox, it's a red outline). But it waits until you press submit to show that it's invalid.

Now try this one. It's identical, except that there's some css:

input:invalid{
    border-color:orange
}

Except this time the orange border color is applied even before submit is pressed. So if and only if you manually set an invalid style for a form, the browser applies it before, which is not intuitive behavior. Of course a required field will invalid before you enter anything.

Is there a way to fix this?

like image 334
J-bob Avatar asked Nov 19 '14 16:11

J-bob


People also ask

What happens in case invalid CSS property is used?

The :invalid selector selects form elements with a value that does not validate according to the element's settings.

Which is the invalid field in HTML5?

setCustomValidity("Invalid field."); will make the field invalid. field. setCustomValidity(""); will make the field valid unless it fails an HTML5 constraint. Also, if you want the browser's validity message to show up on input or blur you can use field.

Which one is not a valid selector in CSS?

The :invalid selector allows you to select <input> elements that do not contain valid content, as determined by its type attribute. :invalid is defined in the CSS Selectors Level 3 spec as a “validity pseudo-selector”, meaning it is used to style interactive elements based on an evaluation of user input.

How do you style input required?

The :required selector selects form elements which are required. Form elements with a required attribute are defined as required. Note: The :required selector only applies to the form elements: input, select and textarea. Tip: Use the :optional selector to select form elements which are optional.


1 Answers

Here's what you're looking for: http://jsfiddle.net/CaseyRule/16fuhf6r/2/

Style it like this:

form.submitted input:invalid{
    border-color:orange
}

And then add this js:

$('input[type="submit"]').click( function(){
    $('form').addClass('submitted');
});

I don't believe there is a way to achieve this yet without javascript.

like image 147
Casey Rule Avatar answered Oct 04 '22 18:10

Casey Rule