validator.php 16 KB

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