As I work on creating an address form for my web application, I find myself struggling to define the styling rules for HTML5 form validation that includes the required
attribute. The examples and behaviors discussed below are all specific to Firefox.
The HTML code for the initial input field in the form is as follows:
<label for="addressLine1" class="form__label">
Address Line 1
</label>
<input type="text" required aria-required="true" class="form__input-text" id="addressLine1"/>
Without any custom styling, the behavior of the input is described as follows:
- Upon page loading, the input field presents default styling for a text input
https://i.sstatic.net/Li29r.png
- If attempting to submit the form with a required input left blank, the browser will highlight the input with a red border or shadow
https://i.sstatic.net/JboMY.png
I aim to preserve this behavior where the input initially displays default styling upon load and only switches to "invalid" styling if a user attempts to submit the form with any required fields incomplete. However, determining which attributes/pseudo-classes need adjusting to modify the styling while retaining this behavior has proven challenging. Using the :invalid
pseudo-class results in the following behavior:
- At load, the input already showcases my "invalid" styling due to the field being empty
https://i.sstatic.net/aUcJz.png
- Submitting the form with a blank field adds the red border/shadow atop my existing "invalid" styling
https://i.sstatic.net/udcZE.png
- Only by entering valid data into the input can I achieve my desired default/valid styling
https://i.sstatic.net/fJSZK.png
How can one maintain the default behavior (default styling onload, invalid styling on incorrect submission) with personalized styles? Is it achievable solely through CSS, or must additional JavaScript functionality be implemented?