validator.php 16 KB

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