validator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. return $this->size($attribute, $value) >= $parameters[0] and $this->size($attribute, $value) <= $parameters[1];
  261. }
  262. /**
  263. * Validate the size of an attribute is greater than a minimum value.
  264. *
  265. * @param string $attribute
  266. * @param mixed $value
  267. * @param array $parameters
  268. * @return bool
  269. */
  270. protected function validate_min($attribute, $value, $parameters)
  271. {
  272. return $this->size($attribute, $value) >= $parameters[0];
  273. }
  274. /**
  275. * Validate the size of an attribute is less than a maximum value.
  276. *
  277. * @param string $attribute
  278. * @param mixed $value
  279. * @param array $parameters
  280. * @return bool
  281. */
  282. protected function validate_max($attribute, $value, $parameters)
  283. {
  284. return $this->size($attribute, $value) <= $parameters[0];
  285. }
  286. /**
  287. * Get the size of an attribute.
  288. *
  289. * This method will determine if the attribute is a number, string, or file and
  290. * return the proper size accordingly. If it is a number, then number itself is
  291. * the size; if it is a file, the size is kilobytes in the size; if it is a
  292. * string, the length is the size.
  293. *
  294. * @param string $attribute
  295. * @param mixed $value
  296. * @return mixed
  297. */
  298. protected function size($attribute, $value)
  299. {
  300. if (is_numeric($value) and $this->has_rule($attribute, $this->numeric_rules))
  301. {
  302. return $this->attributes[$attribute];
  303. }
  304. elseif (array_key_exists($attribute, Input::file()))
  305. {
  306. return $value['size'] / 1024;
  307. }
  308. else
  309. {
  310. return Str::length(trim($value));
  311. }
  312. }
  313. /**
  314. * Validate an attribute is contained within a list of values.
  315. *
  316. * @param string $attribute
  317. * @param mixed $value
  318. * @param array $parameters
  319. * @return bool
  320. */
  321. protected function validate_in($attribute, $value, $parameters)
  322. {
  323. return in_array($value, $parameters);
  324. }
  325. /**
  326. * Validate an attribute is not contained within a list of values.
  327. *
  328. * @param string $attribute
  329. * @param mixed $value
  330. * @param array $parameters
  331. * @return bool
  332. */
  333. protected function validate_not_in($attribute, $value, $parameters)
  334. {
  335. return ! in_array($value, $parameters);
  336. }
  337. /**
  338. * Validate the uniqueness of an attribute value on a given database table.
  339. *
  340. * If a database column is not specified, the attribute name will be used.
  341. *
  342. * @param string $attribute
  343. * @param mixed $value
  344. * @param array $parameters
  345. * @return bool
  346. */
  347. protected function validate_unique($attribute, $value, $parameters)
  348. {
  349. if ( ! isset($parameters[1])) $parameters[1] = $attribute;
  350. if (is_null($this->connection)) $this->connection = DB::connection();
  351. return $this->connection->table($parameters[0])->where($parameters[1], '=', $value)->count() == 0;
  352. }
  353. /**
  354. * Validate than an attribute is a valid e-mail address.
  355. *
  356. * @param string $attribute
  357. * @param mixed $value
  358. * @return bool
  359. */
  360. protected function validate_email($attribute, $value)
  361. {
  362. return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
  363. }
  364. /**
  365. * Validate than an attribute is a valid URL.
  366. *
  367. * @param string $attribute
  368. * @param mixed $value
  369. * @return bool
  370. */
  371. protected function validate_url($attribute, $value)
  372. {
  373. return filter_var($value, FILTER_VALIDATE_URL) !== false;
  374. }
  375. /**
  376. * Validate that an attribute is an active URL.
  377. *
  378. * @param string $attribute
  379. * @param mixed $value
  380. * @return bool
  381. */
  382. protected function validate_active_url($attribute, $value)
  383. {
  384. $url = str_replace(array('http://', 'https://', 'ftp://'), '', Str::lower($value));
  385. return checkdnsrr($url);
  386. }
  387. /**
  388. * Validate the MIME type of a file is an image MIME type.
  389. *
  390. * @param string $attribute
  391. * @param mixed $value
  392. * @return bool
  393. */
  394. protected function validate_image($attribute, $value)
  395. {
  396. return $this->validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp'));
  397. }
  398. /**
  399. * Validate than an attribute contains only alphabetic characters.
  400. *
  401. * @param string $attribute
  402. * @param mixed $value
  403. * @return bool
  404. */
  405. protected function validate_alpha($attribute, $value)
  406. {
  407. return preg_match('/^([a-z])+$/i', $value);
  408. }
  409. /**
  410. * Validate than an attribute contains only alpha-numeric characters.
  411. *
  412. * @param string $attribute
  413. * @param mixed $value
  414. * @return bool
  415. */
  416. protected function validate_alpha_num($attribute, $value)
  417. {
  418. return preg_match('/^([a-z0-9])+$/i', $value);
  419. }
  420. /**
  421. * Validate than an attribute contains only alpha-numeric characters, dashes, and underscores.
  422. *
  423. * @param string $attribute
  424. * @param mixed $value
  425. * @return bool
  426. */
  427. protected function validate_alpha_dash($attribute, $value)
  428. {
  429. return preg_match('/^([-a-z0-9_-])+$/i', $value);
  430. }
  431. /**
  432. * Validate the MIME type of a file upload attribute is in a set of MIME types.
  433. *
  434. * @param string $attribute
  435. * @param array $parameters
  436. * @return bool
  437. */
  438. protected function validate_mimes($attribute, $parameters)
  439. {
  440. foreach ($parameters as $extension)
  441. {
  442. if (File::is($extension, $this->attributes[$attribute]['tmp_name'])) return true;
  443. }
  444. return false;
  445. }
  446. /**
  447. * Get the proper error message for an attribute and rule.
  448. *
  449. * @param string $attribute
  450. * @param string $rule
  451. * @return string
  452. */
  453. protected function message($attribute, $rule)
  454. {
  455. // First we'll check for developer specified, attribute specific messages.
  456. // These messages take first priority. They allow the fine-grained tuning
  457. // of error messages for each rule.
  458. if (array_key_exists($attribute.'_'.$rule, $this->messages))
  459. {
  460. return $this->messages[$attribute.'_'.$rule];
  461. }
  462. // Next we'll check for developer specified, rule specific error messages.
  463. // These allow the developer to override the error message for an entire
  464. // rule, regardless of the attribute being validated by that rule.
  465. elseif (array_key_exists($rule, $this->messages))
  466. {
  467. return $this->messages[$rule];
  468. }
  469. // If the rule being validated is a "size" rule and the attribute is not
  470. // a number, we will need to gather the specific size message for the
  471. // type of attribute being validated, either a file or a string.
  472. elseif (in_array($rule, $this->size_rules) and ! $this->has_rule($attribute, $this->numeric_rules))
  473. {
  474. $line = (array_key_exists($attribute, Input::file())) ? "file" : "string";
  475. return Lang::line("validation.{$rule}.{$line}")->get($this->language);
  476. }
  477. // If no developer specified messages have been set, and no other special
  478. // messages apply to the rule, we will just pull the default validation
  479. // message from the validation language file.
  480. else
  481. {
  482. return Lang::line("validation.{$rule}")->get($this->language);
  483. }
  484. }
  485. /**
  486. * Replace all error message place-holders with actual values.
  487. *
  488. * @param string $message
  489. * @param string $attribute
  490. * @param string $rule
  491. * @param array $parameters
  492. * @return string
  493. */
  494. protected function replace($message, $attribute, $rule, $parameters)
  495. {
  496. $message = str_replace(':attribute', $this->attribute($attribute), $message);
  497. if (in_array($rule, $this->size_rules))
  498. {
  499. // Even though every size rule will not have a place-holder for min,
  500. // max, and size, we will go ahead and make replacements for all of
  501. // them just for convenience. Except for "between" every replacement
  502. // should be the first parameter.
  503. $max = ($rule == 'between') ? $parameters[1] : $parameters[0];
  504. $replace = array($parameters[0], $parameters[0], $max);
  505. $message = str_replace(array(':size', ':min', ':max'), $replace, $message);
  506. }
  507. elseif (in_array($rule, $this->inclusion_rules))
  508. {
  509. $message = str_replace(':values', implode(', ', $parameters), $message);
  510. }
  511. return $message;
  512. }
  513. /**
  514. * Get the displayable name for a given attribute.
  515. *
  516. * Storing attribute names in the language file allows a more reader friendly
  517. * version of the attribute name to be place in the :attribute place-holder.
  518. *
  519. * If no language line is specified for the attribute, a default formatting
  520. * will be used for the attribute.
  521. *
  522. * @param string $attribute
  523. * @return string
  524. */
  525. protected function attribute($attribute)
  526. {
  527. $display = Lang::line('validation.attributes.'.$attribute)->get($this->language);
  528. return (is_null($display)) ? str_replace('_', ' ', $attribute) : $display;
  529. }
  530. /**
  531. * Determine if an attribute has a rule assigned to it.
  532. *
  533. * @param string $attribute
  534. * @param array $rules
  535. * @return bool
  536. */
  537. protected function has_rule($attribute, $rules)
  538. {
  539. foreach ($this->rules[$attribute] as $rule)
  540. {
  541. list($rule, $parameters) = $this->parse($rule);
  542. if (in_array($rule, $rules)) return true;
  543. }
  544. return false;
  545. }
  546. /**
  547. * Extract the rule name and parameters from a rule.
  548. *
  549. * @param string $rule
  550. * @return array
  551. */
  552. protected function parse($rule)
  553. {
  554. $parameters = array();
  555. // The format for specifying validation rules and parameters follows
  556. // a {rule}:{parameters} convention. For instance, "max:3" specifies
  557. // that the value may only be 3 characters in length.
  558. if (($colon = strpos($rule, ':')) !== false)
  559. {
  560. $parameters = explode(',', substr($rule, $colon + 1));
  561. }
  562. return array(is_numeric($colon) ? substr($rule, 0, $colon) : $rule, $parameters);
  563. }
  564. /**
  565. * Set the language that should be used when retrieving error messages.
  566. *
  567. * @param string $language
  568. * @return Validator
  569. */
  570. public function speaks($language)
  571. {
  572. $this->language = $language;
  573. return $this;
  574. }
  575. /**
  576. * Set the database connection that should be used by the validator.
  577. *
  578. * @param Database\Connection $connection
  579. * @return Validator
  580. */
  581. public function connection(\Laravel\Database\Connection $connection)
  582. {
  583. $this->connection = $connection;
  584. return $this;
  585. }
  586. /**
  587. * Dynamically handle calls to custom registered validators.
  588. */
  589. public function __call($method, $parameters)
  590. {
  591. // First we will slice the "validate_" prefix off of the validator
  592. // since customvalidators aren't registered with such a prefix.
  593. if (isset(static::$validators[$method = substr($method, 9)]))
  594. {
  595. return call_user_func_array(static::$validators[$method], $parameters);
  596. }
  597. throw new \Exception("Call to undefined method [$method] on Validator instance.");
  598. }
  599. }