Sub topic 1
HTML Form Validation: Built-in Constraints, the Constraint Validation API, and Server Checks
Prerequisites
You should know basic HTML forms, labels, and inputs, basic CSS selectors, JavaScript event handlers, and how form data reaches a server.
Why validate forms, and where
Validation checks whether submitted data has the expected shape and meaning. It helps users fix mistakes before sending a form. For example, a browser can identify a missing email address immediately.
Client-side validation runs in the browser. It improves usability, but it is not a security boundary. Users can disable it, change the page, or send an HTTP request directly.
Server-side validation runs on your server and is the source of truth. Repeat every important rule there before saving data, sending email, or performing an action.
> callout note > Treat browser validation as helpful guidance. Treat server validation as required protection.
Form controls and submission refresher
A form control is submitted only when it has a name and is successful, such as an enabled input with a value. The name becomes the key in the submitted data. A label identifies the control for users and assistive technology.
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<button type="submit">Sign up</button>
</form>Built-in constraint attributes
HTML constraints let the browser reject common mistakes without custom JavaScript.
| Attribute | Purpose |
|---|---|
| `required` | Requires a value |
| `minlength`, `maxlength` | Limits text length |
| `min`, `max`, `step` | Limits numeric or date values |
| `pattern` | Requires a regular-expression match |
pattern matches the control's value, so document the expected format clearly. These constraints affect browser submission, but the server must apply equivalent rules.
Input types that validate for you
Choose the narrowest accurate type. email checks email-like syntax, url checks URL syntax, number supports numeric ranges, and date supports date input and date constraints. The browser may also provide an appropriate keyboard or picker.
Exercise
Why must a server validate a value that already passed a browser constraint?
Show answer
A client can bypass or modify browser checks, so only server validation can protect the application.