Skip to content
Herby Design

Laravel Validation: A Beginner’s Guide to Safer Forms

Learn Laravel validation with a practical form example, clear rules, Blade error messages, form requests, and beginner-friendly testing steps.

H Hernan MalubayWeb Developer 7 min read Share

Laravel form validation helps you reject missing or incorrectly formatted data before it reaches your application logic. Start with a few rules on the request, then move them into a form request when the rules or authorization checks grow. This Laravel validation guide walks through a beginner-friendly contact form example and shows how to test failures safely.

Key takeaways

  • Validate input on the server, even when the browser also checks fields.
  • Use clear rules for required fields, email addresses, and text length.
  • Move growing validation logic into a form request.
  • Show useful errors without exposing private data.

What Laravel validation does

Validation checks whether incoming data follows rules you choose. For example, a contact form may require a name, a valid email address, and a message under a set length.

Laravel can automatically return a response when validation fails. For a regular web form, it typically redirects back and makes validation errors available to the view. For JSON requests, it can return a structured error response. The exact response depends on the request and your application setup.

Browser-side checks can improve convenience, but they are not a security boundary. A visitor can bypass them, so the server must check the submitted values too.

Laravel validation with a simple example

Suppose a controller handles a contact form submission. Use the request's validate method before saving data or sending an email:

public function store(Request $request)
{
    $validated = $request->validate([
        'name' => ['required', 'string', 'max:100'],
        'email' => ['required', 'email', 'max:255'],
        'message' => ['required', 'string', 'max:5000'],
    ]);

    // Use only the validated data below.
}

Import the request class if it is not already present: use Illuminate\Http\Request;. The rules are arrays, which makes it easy to add or remove individual checks.

Here, required means the field must be present and not empty. string expects text, while max limits its length. The email rule checks that the value has an email-like format; it does not prove that the address belongs to the person submitting it.

Laravel stops the normal controller flow when validation fails. If it passes, the validated values are returned in $validated. Prefer that array over reading every submitted field directly from the request.

Choose rules that fit each field

Rules should describe what your application can safely accept, not what you hope users will submit. Begin with the smallest sensible set, then add rules for your actual business needs.

  • Required text: combine required, string, and a reasonable max.
  • Email: use email, and set a length limit that suits your field.
  • Optional value: use nullable when an empty value is allowed, then apply its other rules when provided.
  • Choice from a list: use in when accepted values are fixed, such as in:standard,express.

Do not assume that every field should be required. For example, a second address line may be optional. Choose rules based on the user journey and how the data will be used.

For more complex checks, consult the official Laravel validation documentation. Check the documentation for your installed Laravel version before copying an example, as available rules and configuration can change.

Display errors in a Blade form

Validation should guide a visitor toward a successful submission. In a Blade template, you can check for a field-specific error and show it near the relevant input:

<label for="email">Email</label>
<input id="email" name="email" type="email" value="{{ old('email') }}">

@error('email')
    <p>{{ $message }}</p>
@enderror

old('email') repopulates the previous value after a validation redirect. Showing it saves the visitor from entering everything again. Avoid repopulating sensitive fields, such as passwords.

Keep the error text clear and close to its field. You can also show a short summary at the top of a long form. Use accessible labels and ensure errors are not communicated by color alone.

Laravel provides default error messages, and you can customize messages when needed. Keep custom wording direct: explain what needs to change, such as “Please enter a valid email address.” Avoid revealing internal database details or implementation notes.

Move rules into a form request

A short controller can use $request->validate(). If validation rules become lengthy or need an authorization check, create a dedicated form request. This keeps request concerns out of the controller.

Generate one with Artisan:

php artisan make:request StoreContactRequest

Laravel creates a request class under app/Http/Requests. Define its authorization decision and rules, then type-hint it in the controller method:

public function rules(): array
{
    return [
        'name' => ['required', 'string', 'max:100'],
        'email' => ['required', 'email', 'max:255'],
        'message' => ['required', 'string', 'max:5000'],
    ];
}

For a public contact form, the request may allow anyone to submit. For an edit action, authorization should check whether the signed-in user may change that record. Do not treat validation as permission checking; they solve different problems.

Then use the request class in the controller method and access its validated data. See the official form request documentation for the current structure and options.

Test both accepted and rejected input

A form that works for one valid submission may still mishandle empty fields, long text, or malformed input. Test expected success and failure cases before relying on it.

  1. Submit a complete, valid form and confirm it reaches the expected next step.
  2. Leave each required field empty and confirm a useful error appears.
  3. Try an invalid email and text beyond the chosen length limit.
  4. Submit optional fields both empty and filled.
  5. Check that validation failures do not save partial or unintended data.

Laravel's testing tools can make these checks repeatable. Start with the documentation for HTTP tests, and adapt examples to your app's version and routes.

During development, use test data rather than real customer information. Never test destructive database commands against a production database. If you are building a larger app, this custom web application development service page offers context on application work, and you can explore Laravel development support.

Common beginner mistakes to avoid

One common mistake is relying only on JavaScript or HTML attributes. These checks help users, but server-side validation is still essential because requests can be sent without the page interface.

Another is accepting every request field for mass assignment. Validate the fields you expect, then pass only those validated values to the next step. This helps prevent unexpected fields from being processed.

A third mistake is writing rules that are too loose or too strict. A tiny maximum may block legitimate messages, while no limit can invite unnecessarily large submissions. Choose limits that fit the feature and review them if requirements change.

Finally, avoid putting every rule in a crowded controller. A form request is useful when the rules need a clear home, but there is no need to create extra classes for a tiny one-off form. Keep the structure proportional to the task.

Frequently asked questions

Does Laravel validate forms automatically?

No. You must define rules using a request validation method, a form request, or another validator approach. Laravel then handles the failure response according to the request type and application configuration.

Should I validate in the browser or on the server?

Use both when useful. Browser checks offer quick feedback, while server checks protect the application and remain necessary for every submitted value.

When should I create a form request?

Use one when rules are growing, reused, or easier to manage outside the controller. It can also hold authorization logic for the action.

Can I customize Laravel validation messages?

Yes. Laravel supports custom messages and attribute names. Keep them specific and helpful, and consult the documentation for the syntax in your installed version.

Does a valid email rule confirm that an address exists?

No. It checks formatting, not ownership or deliverability. If you need to confirm ownership, use a separate email verification process.

Start with one form

Build confidence by adding Laravel validation to one small form, displaying clear errors, and testing both valid and invalid submissions. When your application needs a broader plan, contact Herby Design to discuss your Laravel project.

Found this helpful? Share it

New to Laravel validation? Learn how to make forms safer with clear rules, Blade error messages, form requests, and testing tips.#Laravel #PHP #FormValidation #WebDevelopment #SmallBusiness

Need help with your website?

I build fast, SEO-ready websites and web applications.

Discuss your project
Laravel Tutorials 7 min read

Laravel Service Container Basics for Beginners

Learn Laravel service container basics with beginner-friendly examples of dependency injection, interface bindings, and testing choices.

Read article
Business and Online Solutions 7 min read

AI Prompts: Useful Templates for Small Businesses

Use practical AI prompt templates for customer replies, social posts, and website copy—plus simple checks to keep results accurate and safe.

Read article