validator.php 16 KB

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