validator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. <?php namespace Laravel\Validation;
  2. use Closure;
  3. use Laravel\Arr;
  4. use Laravel\IoC;
  5. use Laravel\Str;
  6. use Laravel\Lang;
  7. use Laravel\Input;
  8. use Laravel\Database\Manager as DB;
  9. class Validator {
  10. /**
  11. * The database connection that should be used by the validator.
  12. *
  13. * @var Database\Connection
  14. */
  15. public $connection;
  16. /**
  17. * The array being validated.
  18. *
  19. * @var array
  20. */
  21. public $attributes;
  22. /**
  23. * The post-validation error messages.
  24. *
  25. * @var Messages
  26. */
  27. public $errors;
  28. /**
  29. * The validation rules.
  30. *
  31. * @var array
  32. */
  33. protected $rules = array();
  34. /**
  35. * The validation messages.
  36. *
  37. * @var array
  38. */
  39. protected $messages = array();
  40. /**
  41. * The language that should be used when retrieving error messages.
  42. *
  43. * @var string
  44. */
  45. protected $language;
  46. /**
  47. * The size related validation rules.
  48. *
  49. * @var array
  50. */
  51. protected $size_rules = array('size', 'between', 'min', 'max');
  52. /**
  53. * The inclusion related validation rules.
  54. *
  55. * @var array
  56. */
  57. protected $inclusion_rules = array('in', 'not_in', 'mimes');
  58. /**
  59. * The numeric related validation rules.
  60. *
  61. * @var array
  62. */
  63. protected $numeric_rules = array('numeric', 'integer');
  64. /**
  65. * The registered custom validators.
  66. *
  67. * @var array
  68. */
  69. protected static $validators = array();
  70. /**
  71. * Create a new validator instance.
  72. *
  73. * @param array $attributes
  74. * @param array $rules
  75. * @param array $messages
  76. * @return void
  77. */
  78. public function __construct($attributes, $rules, $messages = array())
  79. {
  80. foreach ($rules as $key => &$rule)
  81. {
  82. $rule = (is_string($rule)) ? explode('|', $rule) : $rule;
  83. }
  84. $this->rules = $rules;
  85. $this->messages = $messages;
  86. $this->attributes = $attributes;
  87. }
  88. /**
  89. * Create a new validator instance.
  90. *
  91. * @param array $attributes
  92. * @param array $rules
  93. * @param array $messages
  94. * @return Validator
  95. */
  96. public static function make($attributes, $rules, $messages = array())
  97. {
  98. return new static($attributes, $rules, $messages);
  99. }
  100. /**
  101. * Register a custom validator.
  102. *
  103. * @param string $name
  104. * @param Closure $validator
  105. * @return void
  106. */
  107. public static function register($name, $validator)
  108. {
  109. static::$validators[$name] = $validator;
  110. }
  111. /**
  112. * Validate the target array using the specified validation rules.
  113. *
  114. * @return bool
  115. */
  116. public function invalid()
  117. {
  118. return ! $this->valid();
  119. }
  120. /**
  121. * Validate the target array using the specified validation rules.
  122. *
  123. * @return bool
  124. */
  125. public function valid()
  126. {
  127. $this->errors = new Messages;
  128. foreach ($this->rules as $attribute => $rules)
  129. {
  130. foreach ($rules as $rule) $this->check($attribute, $rule);
  131. }
  132. return count($this->errors->messages) == 0;
  133. }
  134. /**
  135. * Evaluate an attribute against a validation rule.
  136. *
  137. * @param string $attribute
  138. * @param string $rule
  139. * @return void
  140. */
  141. protected function check($attribute, $rule)
  142. {
  143. list($rule, $parameters) = $this->parse($rule);
  144. $value = Arr::get($this->attributes, $attribute);
  145. if ( ! $this->validatable($rule, $attribute, $value)) return;
  146. if ( ! $this->{'validate_'.$rule}($attribute, $value, $parameters, $this))
  147. {
  148. $this->error($attribute, $rule, $parameters);
  149. }
  150. }
  151. /**
  152. * Determine if an attribute is validatable.
  153. *
  154. * To be considered validatable, the attribute must either exist, or the
  155. * rule being checked must implicitly validate "required", such as the
  156. * "required" rule or the "accepted" rule.
  157. *
  158. * @param string $rule
  159. * @param string $attribute
  160. * @param mixed $value
  161. * @return bool
  162. */
  163. protected function validatable($rule, $attribute, $value)
  164. {
  165. return ($this->validate_required($attribute, $value) or in_array($rule, array('required', 'accepted')));
  166. }
  167. /**
  168. * Add an error message to the validator's collection of messages.
  169. *
  170. * @param string $attribute
  171. * @param string $rule
  172. * @param array $parameters
  173. * @return void
  174. */
  175. protected function error($attribute, $rule, $parameters)
  176. {
  177. $message = $this->replace($this->message($attribute, $rule), $attribute, $rule, $parameters);
  178. $this->errors->add($attribute, $message);
  179. }
  180. /**
  181. * Validate that a required attribute exists in the attributes array.
  182. *
  183. * @param string $attribute
  184. * @param mixed $value
  185. * @return bool
  186. */
  187. protected function validate_required($attribute, $value)
  188. {
  189. return ! (is_null($value) or (is_string($value) and trim($value) === ''));
  190. }
  191. /**
  192. * Validate that an attribute has a matching confirmation attribute.
  193. *
  194. * @param string $attribute
  195. * @param mixed $value
  196. * @return bool
  197. */
  198. protected function validate_confirmed($attribute, $value)
  199. {
  200. $confirmation = $this->attributes[$attribute.'_confirmation'];
  201. return array_key_exists($attribute.'_confirmation', $this->attributes) and $value == $confirmation;
  202. }
  203. /**
  204. * Validate that an attribute was "accepted".
  205. *
  206. * This validation rule implies the attribute is "required".
  207. *
  208. * @param string $attribute
  209. * @param mixed $value
  210. * @return bool
  211. */
  212. protected function validate_accepted($attribute, $value)
  213. {
  214. return $this->validate_required($attribute) and ($value == 'yes' or $value == '1');
  215. }
  216. /**
  217. * Validate that an attribute is numeric.
  218. *
  219. * @param string $attribute
  220. * @param mixed $value
  221. * @return bool
  222. */
  223. protected function validate_numeric($attribute, $value)
  224. {
  225. return is_numeric($value);
  226. }
  227. /**
  228. * Validate that an attribute is an integer.
  229. *
  230. * @param string $attribute
  231. * @param mixed $value
  232. * @return bool
  233. */
  234. protected function validate_integer($attribute, $value)
  235. {
  236. return filter_var($value, FILTER_VALIDATE_INT) !== false;
  237. }
  238. /**
  239. * Validate the size of an attribute.
  240. *
  241. * @param string $attribute
  242. * @param mixed $value
  243. * @param array $parameters
  244. * @return bool
  245. */
  246. protected function validate_size($attribute, $value, $parameters)
  247. {
  248. return $this->size($attribute, $value) == $parameters[0];
  249. }
  250. /**
  251. * Validate the size of an attribute is between a set of values.
  252. *
  253. * @param string $attribute
  254. * @param mixed $value
  255. * @param array $parameters
  256. * @return bool
  257. */
  258. protected function validate_between($attribute, $value, $parameters)
  259. {
  260. $size = $this->size($attribute, $value);
  261. return $size >= $parameters[0] and $size <= $parameters[1];
  262. }
  263. /**
  264. * Validate the size of an attribute is greater than a minimum value.
  265. *
  266. * @param string $attribute
  267. * @param mixed $value
  268. * @param array $parameters
  269. * @return bool
  270. */
  271. protected function validate_min($attribute, $value, $parameters)
  272. {
  273. return $this->size($attribute, $value) >= $parameters[0];
  274. }
  275. /**
  276. * Validate the size of an attribute is less than a maximum value.
  277. *
  278. * @param string $attribute
  279. * @param mixed $value
  280. * @param array $parameters
  281. * @return bool
  282. */
  283. protected function validate_max($attribute, $value, $parameters)
  284. {
  285. return $this->size($attribute, $value) <= $parameters[0];
  286. }
  287. /**
  288. * Get the size of an attribute.
  289. *
  290. * This method will determine if the attribute is a number, string, or file and
  291. * return the proper size accordingly. If it is a number, then number itself is
  292. * the size; if it is a file, the size is kilobytes in the size; if it is a
  293. * string, the length is the size.
  294. *
  295. * @param string $attribute
  296. * @param mixed $value
  297. * @return mixed
  298. */
  299. protected function size($attribute, $value)
  300. {
  301. if (is_numeric($value) and $this->has_rule($attribute, $this->numeric_rules))
  302. {
  303. return $this->attributes[$attribute];
  304. }
  305. elseif (array_key_exists($attribute, Input::file()))
  306. {
  307. return $value['size'] / 1024;
  308. }
  309. else
  310. {
  311. return Str::length(trim($value));
  312. }
  313. }
  314. /**
  315. * Validate an attribute is contained within a list of values.
  316. *
  317. * @param string $attribute
  318. * @param mixed $value
  319. * @param array $parameters
  320. * @return bool
  321. */
  322. protected function validate_in($attribute, $value, $parameters)
  323. {
  324. return in_array($value, $parameters);
  325. }
  326. /**
  327. * Validate an attribute is not contained within a list of values.
  328. *
  329. * @param string $attribute
  330. * @param mixed $value
  331. * @param array $parameters
  332. * @return bool
  333. */
  334. protected function validate_not_in($attribute, $value, $parameters)
  335. {
  336. return ! in_array($value, $parameters);
  337. }
  338. /**
  339. * Validate the uniqueness of an attribute value on a given database table.
  340. *
  341. * If a database column is not specified, the attribute name will be used.
  342. *
  343. * @param string $attribute
  344. * @param mixed $value
  345. * @param array $parameters
  346. * @return bool
  347. */
  348. protected function validate_unique($attribute, $value, $parameters)
  349. {
  350. if ( ! isset($parameters[1])) $parameters[1] = $attribute;
  351. if (is_null($this->connection)) $this->connection = DB::connection();
  352. return $this->connection->table($parameters[0])->where($parameters[1], '=', $value)->count() == 0;
  353. }
  354. /**
  355. * Validate than an attribute is a valid e-mail address.
  356. *
  357. * @param string $attribute
  358. * @param mixed $value
  359. * @return bool
  360. */
  361. protected function validate_email($attribute, $value)
  362. {
  363. return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
  364. }
  365. /**
  366. * Validate than an attribute is a valid URL.
  367. *
  368. * @param string $attribute
  369. * @param mixed $value
  370. * @return bool
  371. */
  372. protected function validate_url($attribute, $value)
  373. {
  374. return filter_var($value, FILTER_VALIDATE_URL) !== false;
  375. }
  376. /**
  377. * Validate that an attribute is an active URL.
  378. *
  379. * @param string $attribute
  380. * @param mixed $value
  381. * @return bool
  382. */
  383. protected function validate_active_url($attribute, $value)
  384. {
  385. $url = str_replace(array('http://', 'https://', 'ftp://'), '', Str::lower($value));
  386. return checkdnsrr($url);
  387. }
  388. /**
  389. * Validate the MIME type of a file is an image MIME type.
  390. *
  391. * @param string $attribute
  392. * @param mixed $value
  393. * @return bool
  394. */
  395. protected function validate_image($attribute, $value)
  396. {
  397. return $this->validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp'));
  398. }
  399. /**
  400. * Validate than an attribute contains only alphabetic characters.
  401. *
  402. * @param string $attribute
  403. * @param mixed $value
  404. * @return bool
  405. */
  406. protected function validate_alpha($attribute, $value)
  407. {
  408. return preg_match('/^([a-z])+$/i', $value);
  409. }
  410. /**
  411. * Validate than an attribute contains only alpha-numeric characters.
  412. *
  413. * @param string $attribute
  414. * @param mixed $value
  415. * @return bool
  416. */
  417. protected function validate_alpha_num($attribute, $value)
  418. {
  419. return preg_match('/^([a-z0-9])+$/i', $value);
  420. }
  421. /**
  422. * Validate than an attribute contains only alpha-numeric characters, dashes, and underscores.
  423. *
  424. * @param string $attribute
  425. * @param mixed $value
  426. * @return bool
  427. */
  428. protected function validate_alpha_dash($attribute, $value)
  429. {
  430. return preg_match('/^([-a-z0-9_-])+$/i', $value);
  431. }
  432. /**
  433. * Validate the MIME type of a file upload attribute is in a set of MIME types.
  434. *
  435. * @param string $attribute
  436. * @param array $parameters
  437. * @return bool
  438. */
  439. protected function validate_mimes($attribute, $parameters)
  440. {
  441. foreach ($parameters as $extension)
  442. {
  443. if (File::is($extension, $this->attributes[$attribute]['tmp_name'])) return true;
  444. }
  445. return false;
  446. }
  447. /**
  448. * Get the proper error message for an attribute and rule.
  449. *
  450. * @param string $attribute
  451. * @param string $rule
  452. * @return string
  453. */
  454. protected function message($attribute, $rule)
  455. {
  456. // First we'll check for developer specified, attribute specific messages.
  457. // These messages take first priority. They allow the fine-grained tuning
  458. // of error messages for each rule.
  459. if (array_key_exists($attribute.'_'.$rule, $this->messages))
  460. {
  461. return $this->messages[$attribute.'_'.$rule];
  462. }
  463. // Next we'll check for developer specified, rule specific error messages.
  464. // These allow the developer to override the error message for an entire
  465. // rule, regardless of the attribute being validated by that rule.
  466. elseif (array_key_exists($rule, $this->messages))
  467. {
  468. return $this->messages[$rule];
  469. }
  470. // If the rule being validated is a "size" rule and the attribute is not
  471. // a number, we will need to gather the specific size message for the
  472. // type of attribute being validated, either a file or a string.
  473. elseif (in_array($rule, $this->size_rules) and ! $this->has_rule($attribute, $this->numeric_rules))
  474. {
  475. $line = (array_key_exists($attribute, Input::file())) ? "file" : "string";
  476. return Lang::line("validation.{$rule}.{$line}")->get($this->language);
  477. }
  478. // If no developer specified messages have been set, and no other special
  479. // messages apply to the rule, we will just pull the default validation
  480. // message from the validation language file.
  481. else
  482. {
  483. return Lang::line("validation.{$rule}")->get($this->language);
  484. }
  485. }
  486. /**
  487. * Replace all error message place-holders with actual values.
  488. *
  489. * @param string $message
  490. * @param string $attribute
  491. * @param string $rule
  492. * @param array $parameters
  493. * @return string
  494. */
  495. protected function replace($message, $attribute, $rule, $parameters)
  496. {
  497. $message = str_replace(':attribute', $this->attribute($attribute), $message);
  498. if (in_array($rule, $this->size_rules))
  499. {
  500. // Even though every size rule will not have a place-holder for min,
  501. // max, and size, we will go ahead and make replacements for all of
  502. // them just for convenience. Except for "between" every replacement
  503. // should be the first parameter.
  504. $max = ($rule == 'between') ? $parameters[1] : $parameters[0];
  505. $replace = array($parameters[0], $parameters[0], $max);
  506. $message = str_replace(array(':size', ':min', ':max'), $replace, $message);
  507. }
  508. elseif (in_array($rule, $this->inclusion_rules))
  509. {
  510. $message = str_replace(':values', implode(', ', $parameters), $message);
  511. }
  512. return $message;
  513. }
  514. /**
  515. * Get the displayable name for a given attribute.
  516. *
  517. * Storing attribute names in the language file allows a more reader friendly
  518. * version of the attribute name to be place in the :attribute place-holder.
  519. *
  520. * If no language line is specified for the attribute, a default formatting
  521. * will be used for the attribute.
  522. *
  523. * @param string $attribute
  524. * @return string
  525. */
  526. protected function attribute($attribute)
  527. {
  528. $display = Lang::line('validation.attributes.'.$attribute)->get($this->language);
  529. return (is_null($display)) ? str_replace('_', ' ', $attribute) : $display;
  530. }
  531. /**
  532. * Determine if an attribute has a rule assigned to it.
  533. *
  534. * @param string $attribute
  535. * @param array $rules
  536. * @return bool
  537. */
  538. protected function has_rule($attribute, $rules)
  539. {
  540. foreach ($this->rules[$attribute] as $rule)
  541. {
  542. list($rule, $parameters) = $this->parse($rule);
  543. if (in_array($rule, $rules)) return true;
  544. }
  545. return false;
  546. }
  547. /**
  548. * Extract the rule name and parameters from a rule.
  549. *
  550. * @param string $rule
  551. * @return array
  552. */
  553. protected function parse($rule)
  554. {
  555. $parameters = array();
  556. // The format for specifying validation rules and parameters follows
  557. // a {rule}:{parameters} convention. For instance, "max:3" specifies
  558. // that the value may only be 3 characters in length.
  559. if (($colon = strpos($rule, ':')) !== false)
  560. {
  561. $parameters = explode(',', substr($rule, $colon + 1));
  562. }
  563. return array(is_numeric($colon) ? substr($rule, 0, $colon) : $rule, $parameters);
  564. }
  565. /**
  566. * Set the language that should be used when retrieving error messages.
  567. *
  568. * @param string $language
  569. * @return Validator
  570. */
  571. public function speaks($language)
  572. {
  573. $this->language = $language;
  574. return $this;
  575. }
  576. /**
  577. * Set the database connection that should be used by the validator.
  578. *
  579. * @param Database\Connection $connection
  580. * @return Validator
  581. */
  582. public function connection(\Laravel\Database\Connection $connection)
  583. {
  584. $this->connection = $connection;
  585. return $this;
  586. }
  587. /**
  588. * Dynamically handle calls to custom registered validators.
  589. */
  590. public function __call($method, $parameters)
  591. {
  592. // First we will slice the "validate_" prefix off of the validator
  593. // since customvalidators aren't registered with such a prefix.
  594. if (isset(static::$validators[$method = substr($method, 9)]))
  595. {
  596. return call_user_func_array(static::$validators[$method], $parameters);
  597. }
  598. throw new \Exception("Call to undefined method [$method] on Validator instance.");
  599. }
  600. }