Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Created May 21, 2016 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/90b71deb1ab3345ddec6eea678ac1571 to your computer and use it in GitHub Desktop.
Save kurozumi/90b71deb1ab3345ddec6eea678ac1571 to your computer and use it in GitHub Desktop.
簡易バリデーター
<?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