Form Validation
Loading "Intro to Form Validation"
Run locally for transcripts
The web
HTML has built-in support for validation of form elements. Among others, here
are some of the attributes you can give form elements to have the browser
validate them for you:
required
- the element must be filled inminlength
- the element must be at least this many charactersmaxlength
- the element must be at most this many charactersmin
- the element must be at least this valuemax
- the element must be at most this valuepattern
- the element must match this regular expression
For example, here's a form with a required text field and a required email
field:
<form>
<label for="name">Name</label>
<input type="text" id="name" required />
<label for="email">Email</label>
<input type="email" id="email" required />
<button type="submit">Submit</button>
</form>
The unfortunate truth here though is that you cannot rely on the browser to
validate your forms for you. Users can easily bypass such validation by manually
adding
novalidate
to the form tag or making the HTTP request directly using
another tool. This is why it's important to validate your forms on the server.
Client-side validation should be seen as a nice progressive enhancement for a
better user experience, not a replacement for server-side validation.As far as the server is concerned, there is no standard way to handle validation
other than to respond with a
400
status code if there are validation errors.
You typically want to respond with the error messages as well and then the
client should display those error messages next to the form elements that failed
validation.There are important accessibility considerations when it comes to form
validation, which we will address in the next exercise.
In Remix
Remix does not have any built-in support for form validation. However, it does
have a nice way to get the error messages the server responds with using
the
useActionData()
hook.