Help us understand the problem. What is going on with this article?

PHP Validation実装メモ

More than 5 years have passed since last update.

単純なバリデーション機能を実装するためのメモ

validate.php
############################################################
/**
 * error messages
 */
############################################################
public $validateMessage = array(
    'required'     => '入力必須です',
    'alphaNumeric' => '半角英数字で入力してください',
    'email'        => 'メールアドレスが不正です',
    'tel'          => '電話番号形式で入力してください',
    'zip'          => '郵便番号形式で入力してください',
    'confirm'      => '入力内容が一致しません',
    //'date'         => '日付形式で入力してください',
    //'decimal'      => '小数点第%s位までの半角数字を入力してください。',
    //'numeric'      => '半角数字で入力してください',
    //'url'          => 'URL形式で入力してください',
    //'isUnique'     => 'この値は既に登録済です',
    //'inList'       => '入力値が正しくありません',
    //'maxLen'       => '入力された文字数が制限を越えています(最大%s文字)',
    //'minLen'       => '入力された文字数が制限未満です(最小%s文字)',
    );

function run($validateRules, $datas) {
    $errorMessage = array();
    foreach ($validateRules as $this->key => $rules) {
        foreach ($rules as $rule) {
            if (isset($errorMessage[$this->key])) continue;

            $rule = $this->_extractOptionFromRule($rule);

            $funcName = '_valid_' . $rule;
            $this->data = (isset($datas[$this->key])) ? $datas[$this->key] : '';

            if (method_exists($this, $funcName)) {
                $result = $this->$funcName();
            }
            /* 独自のバリデーション
            elseif (method_exists($Model, $rule)) {
                $result = $Model->$rule($datas);
            }
            */
            else continue;

            if (!$result) {
                $errorMessage[$this->key] = $this->_setErrorMessage($rule);
            }
        }
    }
    return $errorMessage;
}

# ex. 
# @param  'confirm[confirm_password]'
# @return 'confirm'
# $this->option には Array ( confirm_password )がセットされる
private function _extractOptionFromRule($rule) {
    $this->options = array();
    $pos = strpos($rule, '[');
    if ($pos) {
        $this->options = explode(',', substr($rule, $pos + 1, -1));
        $rule = substr($rule, 0, $pos);
    }
    return $rule;
}

private function _setErrorMessage($rule) {
    if (isset($this->validateMessage[$rule])) {
        $message = $this->validateMessage[$rule];
    }
    else {
        $message = "valid error!";
    }
    return $message;
}


############################################################
/**
 * validation method
 */
############################################################
private function _valid_required() {
    return (!empty($this->data)) ? true : false;
}

private function _valid_alphaNumeric() {
    return (preg_match("/^[a-zA-Z0-9]+$/", $this->data)) ? true : false;
}

private function _valid_email() {
    return (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $this->data)) ? true : false;
}

private function _valid_zip() {
    return (preg_match("/^[0-9]{3}-[0-9]{4}$/", $this->data)) ? true : false;
}

private function _valid_tel() {
    return (preg_match("/^[0-9]{2,4}-[0-9]{2,4}-[0-9]{3,4}$/", $this->data)) ? true : false;
}

private function _valid_confirm() {
    $confirmData = (isset($this->datas[$this->options[0]])) ? $this->datas[$this->options[0]] : '';
    return ($this->data === $confirmData) ? true : false;
}

# ex yyyy-mm-dd
private function _valid_date($this->data) {
    return (preg_match('/^([1-9][0-9]{3})-(0[1-9]{1}|1[0-2]{1})-(0[1-9]{1}|[1-2]{1}[0-9]{1}|3[0-1]{1})$/', $this->data)) ? true : false;
}

Use cases

hogehoge.php
$validateRules = array(
    'addUser' => array(
        'name' => array('required'),
        'tel'  => array('required', 'tel'),
        'zip'  => array('zip'),
            ),
    'updatePass' => array(
        'login_name'       => array('required'),
        'password'         => array('required'),
        'confirm_password' => array('required', 'confirm[password]'),
            )
    );

function addUser() {
    $datas = array(
        'name' => 'userA',
        'zip'  => '123-1234',
    );
    $errorMessage = $this->validate->run($this->validateRules['addUser'], $datas);

    print_r($errorMessage);
    // Array ( [tel] => 入力必須です )
}

function updatePass() {
    $datas = array(
        'login_name'       => 'userA',
        'password'         => 'boss',
        'confirm_password' => 'pass',
    );
    $errorMessage = $this->validate->run($this->validateRules['updatePass'], $datas);

    print_r($errorMessage);
    // Array ( [confirm_password] => 入力内容が一致しません )
}

terumichi1209
WEBエンジニアです!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away