Laravel Validating a Form Field Using an Array

  • June 03, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel supports an impressive number of validators, capable of validating everything from password length to e-mail addresses (see documentation). Some validation capabilities aren't as apparent as others though, such as how to determine whether a submitted value is equivalent to one of a predetermined range of allowable values.

Suppose your user registration form included a select box asking the user how they found out about your site. You've determined there are six possible ways, including a search engine, Twitter, Facebook, user group, friend, or other. This list is going to remain static, and you don't plan on querying it in any manner other than to determine general frequency and trends, and so are just going to manage the values as strings. The select box might look like this:

<select name="how">
    <option value="blank">How did you learn about us?</option>
    <option value="search">Search Engine</option>
    <option value="twitter">Twitter</option>
    <option value="facebook">Facebook</option>
    <option value="user_group">User Group</option>
    <option value="friend">Friend / Colleague</option>
    <option value="other">Other</option>
</select>

Therefore the list of allowable values include search, twitter, facebook, user_group, friend, and other. How can you ensure one of these values has been selected?

Presuming you're using Laravel 5's new form request feature (see this blog post if you're not familiar with this topic), validating this form field as desired is surprisingly easy.

$rules = [
  ...
  'how' => "required|in:search,twitter,facebook,user_group,friend,other",
  ...
]

This rule actually defines two validators. First, we ensure the field is required. That is to say, the field must be included alongside other submitted fields. Second, the field's submitted value must be one of the six predetermined strings.

Need to add or subtract an option? No problem; just add/remove the desired option from the HTML and adjust the validator accordingly.

If you'd like to learn more about Laravel 5 form requests I suggest checking out these other blog posts: