PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/laravel/documentation/validation.md

https://bitbucket.org/Maron1/taqman
Markdown | 485 lines | 285 code | 200 blank | 0 comment | 0 complexity | bc9954ae4cedb272aed3ea9f7ef0ca84 MD5 | raw file
  1. # Validation
  2. ## Contents
  3. - [The Basics](#the-basics)
  4. - [Validation Rules](#validation-rules)
  5. - [Retrieving Error Message](#retrieving-error-messages)
  6. - [Validation Walkthrough](#validation-walkthrough)
  7. - [Custom Error Messages](#custom-error-messages)
  8. - [Custom Validation Rules](#custom-validation-rules)
  9. <a name="the-basics"></a>
  10. ## The Basics
  11. Almost every interactive web application needs to validate data. For instance, a registration form probably requires the password to be confirmed. Maybe the e-mail address must be unique. Validating data can be a cumbersome process. Thankfully, it isn't in Laravel. The Validator class provides an awesome array of validation helpers to make validating your data a breeze. Let's walk through an example:
  12. #### Get an array of data you want to validate:
  13. $input = Input::all();
  14. #### Define the validation rules for your data:
  15. $rules = array(
  16. 'name' => 'required|max:50',
  17. 'email' => 'required|email|unique:users',
  18. );
  19. #### Create a Validator instance and validate the data:
  20. $validation = Validator::make($input, $rules);
  21. if ($validation->fails())
  22. {
  23. return $validation->errors;
  24. }
  25. With the *errors* property, you can access a simple message collector class that makes working with your error messages a piece of cake. Of course, default error messages have been setup for all validation rules. The default messages live at **language/en/validation.php**.
  26. Now you are familiar with the basic usage of the Validator class. You're ready to dig in and learn about the rules you can use to validate your data!
  27. <a name="validation-rules"></a>
  28. ## Validation Rules
  29. - [Required](#rule-required)
  30. - [Alpha, Alpha Numeric, & Alpha Dash](#rule-alpha)
  31. - [Size](#rule-size)
  32. - [Numeric](#rule-numeric)
  33. - [Inclusion & Exclusion](#rule-in)
  34. - [Confirmation](#rule-confirmation)
  35. - [Acceptance](#rule-acceptance)
  36. - [Same & Different](#same-and-different)
  37. - [Regular Expression Match](#regex-match)
  38. - [Uniqueness & Existence](#rule-unique)
  39. - [Dates](#dates)
  40. - [E-Mail Addresses](#rule-email)
  41. - [URLs](#rule-url)
  42. - [Uploads](#rule-uploads)
  43. - [Arrays](#rule-arrays)
  44. <a name="rule-required"></a>
  45. ### Required
  46. #### Validate that an attribute is present and is not an empty string:
  47. 'name' => 'required'
  48. #### Validate that an attribute is present, when another attribute is present:
  49. 'last_name' => 'required_with:first_name'
  50. <a name="rule-alpha"></a>
  51. ### Alpha, Alpha Numeric, & Alpha Dash
  52. #### Validate that an attribute consists solely of letters:
  53. 'name' => 'alpha'
  54. #### Validate that an attribute consists of letters and numbers:
  55. 'username' => 'alpha_num'
  56. #### Validate that an attribute only contains letters, numbers, dashes, or underscores:
  57. 'username' => 'alpha_dash'
  58. <a name="rule-size"></a>
  59. ### Size
  60. #### Validate that an attribute is a given length, or, if an attribute is numeric, is a given value:
  61. 'name' => 'size:10'
  62. #### Validate that an attribute size is within a given range:
  63. 'payment' => 'between:10,50'
  64. > **Note:** All minimum and maximum checks are inclusive.
  65. #### Validate that an attribute is at least a given size:
  66. 'payment' => 'min:10'
  67. #### Validate that an attribute is no greater than a given size:
  68. 'payment' => 'max:50'
  69. <a name="rule-numeric"></a>
  70. ### Numeric
  71. #### Validate that an attribute is numeric:
  72. 'payment' => 'numeric'
  73. #### Validate that an attribute is an integer:
  74. 'payment' => 'integer'
  75. <a name="rule-in"></a>
  76. ### Inclusion & Exclusion
  77. #### Validate that an attribute is contained in a list of values:
  78. 'size' => 'in:small,medium,large'
  79. #### Validate that an attribute is not contained in a list of values:
  80. 'language' => 'not_in:cobol,assembler'
  81. <a name="rule-confirmation"></a>
  82. ### Confirmation
  83. The *confirmed* rule validates that, for a given attribute, a matching *attribute_confirmation* attribute exists.
  84. #### Validate that an attribute is confirmed:
  85. 'password' => 'confirmed'
  86. Given this example, the Validator will make sure that the *password* attribute matches the *password_confirmation* attribute in the array being validated.
  87. <a name="rule-acceptance"></a>
  88. ### Acceptance
  89. The *accepted* rule validates that an attribute is equal to *yes* or *1*. This rule is helpful for validating checkbox form fields such as "terms of service".
  90. #### Validate that an attribute is accepted:
  91. 'terms' => 'accepted'
  92. <a name="same-and-different"></a>
  93. ## Same & Different
  94. #### Validate that an attribute matches another attribute:
  95. 'token1' => 'same:token2'
  96. #### Validate that two attributes have different values:
  97. 'password' => 'different:old_password',
  98. <a name="regex-match"></a>
  99. ### Regular Expression Match
  100. The *match* rule validates that an attribute matches a given regular expression.
  101. #### Validate that an attribute matches a regular expression:
  102. 'username' => 'match:/[a-z]+/';
  103. <a name="rule-unique"></a>
  104. ### Uniqueness & Existence
  105. #### Validate that an attribute is unique on a given database table:
  106. 'email' => 'unique:users'
  107. In the example above, the *email* attribute will be checked for uniqueness on the *users* table. Need to verify uniqueness on a column name other than the attribute name? No problem:
  108. #### Specify a custom column name for the unique rule:
  109. 'email' => 'unique:users,email_address'
  110. Many times, when updating a record, you want to use the unique rule, but exclude the row being updated. For example, when updating a user's profile, you may allow them to change their e-mail address. But, when the *unique* rule runs, you want it to skip the given user since they may not have changed their address, thus causing the *unique* rule to fail. It's easy:
  111. #### Forcing the unique rule to ignore a given ID:
  112. 'email' => 'unique:users,email_address,10'
  113. #### Validate that an attribute exists on a given database table:
  114. 'state' => 'exists:states'
  115. #### Specify a custom column name for the exists rule:
  116. 'state' => 'exists:states,abbreviation'
  117. <a name="dates"></a>
  118. ### Dates
  119. #### Validate that a date attribute is before a given date:
  120. 'birthdate' => 'before:1986-05-28';
  121. #### Validate that a date attribute is after a given date:
  122. 'birthdate' => 'after:1986-05-28';
  123. > **Note:** The **before** and **after** validation rules use the **strtotime** PHP function to convert your date to something the rule can understand.
  124. #### Validate that a date attribute conforms to a given format:
  125. 'start_date' => 'date_format:H\\:i'),
  126. > **Note:** The backslash escapes the colon so that it does not count as a parameter separator.
  127. The formatting options for the date format are described in the [PHP documentation](http://php.net/manual/en/datetime.createfromformat.php#refsect1-datetime.createfromformat-parameters).
  128. <a name="rule-email"></a>
  129. ### E-Mail Addresses
  130. #### Validate that an attribute is an e-mail address:
  131. 'address' => 'email'
  132. > **Note:** This rule uses the PHP built-in *filter_var* method.
  133. <a name="rule-url"></a>
  134. ### URLs
  135. #### Validate that an attribute is a URL:
  136. 'link' => 'url'
  137. #### Validate that an attribute is an active URL:
  138. 'link' => 'active_url'
  139. > **Note:** The *active_url* rule uses *checkdnsr* to verify the URL is active.
  140. <a name="rule-uploads"></a>
  141. ### Uploads
  142. The *mimes* rule validates that an uploaded file has a given MIME type. This rule uses the PHP Fileinfo extension to read the contents of the file and determine the actual MIME type. Any extension defined in the *config/mimes.php* file may be passed to this rule as a parameter:
  143. #### Validate that a file is one of the given types:
  144. 'picture' => 'mimes:jpg,gif'
  145. > **Note:** When validating files, be sure to use Input::file() or Input::all() to gather the input.
  146. #### Validate that a file is an image:
  147. 'picture' => 'image'
  148. #### Validate that a file is no more than a given size in kilobytes:
  149. 'picture' => 'image|max:100'
  150. <a name="rule-arrays"></a>
  151. ### Arrays
  152. #### Validate that an attribute is an array
  153. 'categories' => 'array'
  154. #### Validate that an attribute is an array, and has exactly 3 elements
  155. 'categories' => 'array|count:3'
  156. #### Validate that an attribute is an array, and has between 1 and 3 elements
  157. 'categories' => 'array|countbetween:1,3'
  158. #### Validate that an attribute is an array, and has at least 2 elements
  159. 'categories' => 'array|countmin:2'
  160. #### Validate that an attribute is an array, and has at most 2 elements
  161. 'categories' => 'array|countmax:2'
  162. <a name="retrieving-error-messages"></a>
  163. ## Retrieving Error Messages
  164. Laravel makes working with your error messages a cinch using a simple error collector class. After calling the *passes* or *fails* method on a Validator instance, you may access the errors via the *errors* property. The error collector has several simple functions for retrieving your messages:
  165. #### Determine if an attribute has an error message:
  166. if ($validation->errors->has('email'))
  167. {
  168. // The e-mail attribute has errors…
  169. }
  170. #### Retrieve the first error message for an attribute:
  171. echo $validation->errors->first('email');
  172. Sometimes you may need to format the error message by wrapping it in HTML. No problem. Along with the :message place-holder, pass the format as the second parameter to the method.
  173. #### Format an error message:
  174. echo $validation->errors->first('email', '<p>:message</p>');
  175. #### Get all of the error messages for a given attribute:
  176. $messages = $validation->errors->get('email');
  177. #### Format all of the error messages for an attribute:
  178. $messages = $validation->errors->get('email', '<p>:message</p>');
  179. #### Get all of the error messages for all attributes:
  180. $messages = $validation->errors->all();
  181. #### Format all of the error messages for all attributes:
  182. $messages = $validation->errors->all('<p>:message</p>');
  183. <a name="validation-walkthrough"></a>
  184. ## Validation Walkthrough
  185. Once you have performed your validation, you need an easy way to get the errors back to the view. Laravel makes it amazingly simple. Let's walk through a typical scenario. We'll define two routes:
  186. Route::get('register', function()
  187. {
  188. return View::make('user.register');
  189. });
  190. Route::post('register', function()
  191. {
  192. $rules = array();
  193. $validation = Validator::make(Input::all(), $rules);
  194. if ($validation->fails())
  195. {
  196. return Redirect::to('register')->with_errors($validation);
  197. }
  198. });
  199. Great! So, we have two simple registration routes. One to handle displaying the form, and one to handle the posting of the form. In the POST route, we run some validation over the input. If the validation fails, we redirect back to the registration form and flash the validation errors to the session so they will be available for us to display.
  200. **But, notice we are not explicitly binding the errors to the view in our GET route**. However, an errors variable ($errors) will still be available in the view. Laravel intelligently determines if errors exist in the session, and if they do, binds them to the view for you. If no errors exist in the session, an empty message container will still be bound to the view. In your views, this allows you to always assume you have a message container available via the errors variable. We love making your life easier.
  201. For example, if email address validation failed, we can look for 'email' within the $errors session var.
  202. $errors->has('email')
  203. Using Blade, we can then conditionally add error messages to our view.
  204. {{ $errors->has('email') ? 'Invalid Email Address' : 'Condition is false. Can be left blank' }}
  205. This will also work great when we need to conditionally add classes when using something like Twitter Bootstrap.
  206. For example, if the email address failed validation, we may want to add the "error" class from Bootstrap to our *div class="control-group"* statement.
  207. <div class="control-group {{ $errors->has('email') ? 'error' : '' }}">
  208. When the validation fails, our rendered view will have the appended *error* class.
  209. <div class="control-group error">
  210. <a name="custom-error-messages"></a>
  211. ## Custom Error Messages
  212. Want to use an error message other than the default? Maybe you even want to use a custom error message for a given attribute and rule. Either way, the Validator class makes it easy.
  213. #### Create an array of custom messages for the Validator:
  214. $messages = array(
  215. 'required' => 'The :attribute field is required.',
  216. );
  217. $validation = Validator::make(Input::get(), $rules, $messages);
  218. Great! Now our custom message will be used anytime a required validation check fails. But, what is this **:attribute** stuff in our message? To make your life easier, the Validator class will replace the **:attribute** place-holder with the actual name of the attribute! It will even remove underscores from the attribute name.
  219. You may also use the **:other**, **:size**, **:min**, **:max**, and **:values** place-holders when constructing your error messages:
  220. #### Other validation message place-holders:
  221. $messages = array(
  222. 'same' => 'The :attribute and :other must match.',
  223. 'size' => 'The :attribute must be exactly :size.',
  224. 'between' => 'The :attribute must be between :min - :max.',
  225. 'in' => 'The :attribute must be one of the following types: :values',
  226. );
  227. So, what if you need to specify a custom required message, but only for the email attribute? No problem. Just specify the message using an **attribute_rule** naming convention:
  228. #### Specifying a custom error message for a given attribute:
  229. $messages = array(
  230. 'email_required' => 'We need to know your e-mail address!',
  231. );
  232. In the example above, the custom required message will be used for the email attribute, while the default message will be used for all other attributes.
  233. However, if you are using many custom error messages, specifying inline may become cumbersome and messy. For that reason, you can specify your custom messages in the **custom** array within the validation language file:
  234. #### Adding custom error messages to the validation language file:
  235. 'custom' => array(
  236. 'email_required' => 'We need to know your e-mail address!',
  237. )
  238. <a name="custom-validation-rules"></a>
  239. ## Custom Validation Rules
  240. Laravel provides a number of powerful validation rules. However, it's very likely that you'll need to eventually create some of your own. There are two simple methods for creating validation rules. Both are solid so use whichever you think best fits your project.
  241. #### Registering a custom validation rule:
  242. Validator::register('awesome', function($attribute, $value, $parameters)
  243. {
  244. return $value == 'awesome';
  245. });
  246. In this example we're registering a new validation rule with the validator. The rule receives three arguments. The first is the name of the attribute being validated, the second is the value of the attribute being validated, and the third is an array of parameters that were specified for the rule.
  247. Here is how your custom validation rule looks when called:
  248. $rules = array(
  249. 'username' => 'required|awesome',
  250. );
  251. Of course, you will need to define an error message for your new rule. You can do this either in an ad-hoc messages array:
  252. $messages = array(
  253. 'awesome' => 'The attribute value must be awesome!',
  254. );
  255. $validator = Validator::make(Input::get(), $rules, $messages);
  256. Or by adding an entry for your rule in the **language/en/validation.php** file:
  257. 'awesome' => 'The attribute value must be awesome!',
  258. As mentioned above, you may even specify and receive a list of parameters in your custom rule:
  259. // When building your rules array…
  260. $rules = array(
  261. 'username' => 'required|awesome:yes',
  262. );
  263. // In your custom rule…
  264. Validator::register('awesome', function($attribute, $value, $parameters)
  265. {
  266. return $value == $parameters[0];
  267. });
  268. In this case, the parameters argument of your validation rule would receive an array containing one element: "yes".
  269. Another method for creating and storing custom validation rules is to extend the Validator class itself. By extending the class you create a new version of the validator that has all of the pre-existing functionality combined with your own custom additions. You can even choose to replace some of the default methods if you'd like. Let's look at an example:
  270. First, create a class that extends **Laravel\Validator** and place it in your **application/libraries** directory:
  271. #### Defining a custom validator class:
  272. <?php
  273. class Validator extends Laravel\Validator {}
  274. Next, remove the Validator alias from **config/application.php**. This is necessary so that you don't end up with 2 classes named "Validator" which will certainly conflict with one another.
  275. Next, let's take our "awesome" rule and define it in our new class:
  276. #### Adding a custom validation rule:
  277. <?php
  278. class Validator extends Laravel\Validator {
  279. public function validate_awesome($attribute, $value, $parameters)
  280. {
  281. return $value == 'awesome';
  282. }
  283. }
  284. Notice that the method is named using the **validate_rule** naming convention. The rule is named "awesome" so the method must be named "validate_awesome". This is one way in which registering your custom rules and extending the Validator class are different. Validator classes simply need to return true or false. That's it!
  285. Keep in mind that you'll still need to create a custom message for any validation rules that you create. The method for doing so is the same no matter how you define your rule!