簡易バリデーター
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Validator; | |
class Validator | |
{ | |
/** | |
* バリデーションルールの設定 | |
* | |
* @param string $data | |
* @param string $rules | |
* @return boolean | |
*/ | |
public function setRules($data, $rules) | |
{ | |
if(!is_string($rules)) | |
throw new \ErrorException("エラー"); | |
$rules = preg_split('/\|(?![^\[]*\])/', $rules); | |
$required = in_array('required', $rules) ? true : false; | |
foreach ($rules as $rule) | |
{ | |
if (preg_match('/(.*?)\[(.*)\]/', $rule, $match)) | |
{ | |
$rule = $match[1]; | |
$param = $match[2]; | |
return self::{$rule}($data, $param); | |
} | |
else | |
{ | |
return self::{$rule}($data); | |
} | |
} | |
return true; | |
} | |
/** | |
* 必須チェック | |
* | |
* @param string $field | |
* @return boolean | |
*/ | |
protected static function required($data) | |
{ | |
return (bool) (trim($data) !== ''); | |
} | |
/** | |
* 最小文字数チェック | |
* | |
* @param string $field | |
* @param int $val | |
* @return boolean | |
*/ | |
protected static function min_length($data, $val) | |
{ | |
if (!is_numeric($val)) | |
{ | |
return false; | |
} | |
return (bool) ($val <= mb_strlen($data)); | |
} | |
/** | |
* 最大文字数チェック | |
* | |
* @param sting $field | |
* @param int $val | |
* @return boolean | |
*/ | |
protected static function max_length($data, $val) | |
{ | |
if (!is_numeric($val)) | |
{ | |
return false; | |
} | |
return (bool) ($val >= mb_strlen($data)); | |
} | |
/** | |
* 文字数チェック | |
* | |
* @param string $field | |
* @param int $val | |
* @return boolean | |
*/ | |
public function exact_length($data, $val) | |
{ | |
if (!is_numeric($val)) | |
{ | |
return false; | |
} | |
return (bool) (mb_strlen($data) === (int) $val); | |
} | |
/** | |
* メールアドレスチェック | |
* | |
* @param string $data | |
* @return boolean | |
*/ | |
protected static function email($data) | |
{ | |
if (function_exists('idn_to_ascii') && $atpos = strpos($data, '@')) | |
{ | |
$str = substr($str, 0, ++$atpos) . idn_to_ascii(substr($data, $atpos)); | |
} | |
return (bool) filter_var($data, FILTER_VALIDATE_EMAIL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment