This is a solution to the Newsletter sign-up form with success message challenge on Frontend Mentor. Frontend Mentor challenges help you improve your coding skills by building realistic projects.
Users should be able to:
- Add their email and submit the form
- See a success message with their email after successfully submitting the form
- See form validation messages if:
- The field is left empty
- The email address is not formatted correctly
- View the optimal layout for the interface depending on their device's screen size
- See hover and focus states for all interactive elements on the page
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- CSS animation properties
- Mobile-first workflow
- Vanilla JavaScript (DOM)
-
novalidate
: I used thenovalidate
attribute on theform
element to prevent the browser from validating theform
by default. -
role="alert"
,aria-live="polite"
,aria-describedby
andaria-invalid
: I used these to make the error message accessible for screen reader users. -
Constraint validation API
-
HTML: We can use various attributes of form elements (
input
,textarea
) to implement validation. Some of the attributes I liked are:minlength
,maxlength
min
,max
pattern
required
-
CSS: We can use various pseudo-classes in CSS if we want to implement form styling based on validation. Some pseudo-classes I found interesting are:
input:valid { /* Styles for the valid input */ } input:invalid { /* Styles for the invalid input */ }
-
JavaScript: We can use the properties of the
ValidityState
object if we want to control the validation of our form using JavaScript. An example of accessing theValidityState
object in a fictional input could be:console.log(emailField.validity); /* Output { badInput: false, customError: false, patternMismatch: true, rangeOverflow: true, rangeUnderflow: false, stepMismatch: false, tooLong: false, tooShort: true, typeMismatch: false, valid: false, valueMissing: true } */
-
-
Client-side form validation - This MDN article provides a good overview of how to implement your own form validations using JavaScript. I highly recommend it for those starting to learn about this topic.
-
Constraint validation - Specification of the client-side form validation API, great when you need more details to carry out your own validations.
-
Test your skills - These excellent MDN tests can help you practice client-side form validation using JavaScript.
- GitHub - @alberto-rj
- Frontend Mentor - @alberto-rj
- Twitter - @albertorauljose
Thank you very much Grace Snow for the great suggestions you provided. They were useful because they helped me to significantly improve this solution, especially in terms of accessibility and performance.