0% complete

Forms & User Input · Lesson 4 of 6

Form Validation

Reject invalid input on the server and return useful field errors.

Lesson

Client-side constraints improve usability, but only server-side validation can protect application rules. Validate required fields, type, length, format, and allowed values. Report actionable errors without echoing untrusted values, and do not perform a state change until every required field passes. FILTER_VALIDATE_EMAIL checks format; an application may still need verification that the address is owned by the user. Further guidance Treat every submitted field and uploaded file as untrusted. Validate type, length, allowed values, and request method on the server; use CSRF protection for state changes. Escape values for their output context, and never use browser validation as the only safeguard. Practice task: Create a fresh example for Form Validation. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Form Validation
PHP
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false || $email === null) {
    echo 'Enter a valid email address.';
} else {
    echo 'Email format is valid.';
}
Expected output
A validation message for the submitted email

Key points

  • Reject invalid input on the server and return useful field errors.
  • Validate input on the server before processing it.
  • Escape output for its context and protect state-changing forms from CSRF.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.