Varitronライブラリの使い方メモ

ContactページのバリデーションはVaritronを使ってます。

前サイトはZendFramework1で作ってました。だからバリデーションもZF1。

今回のサイトは静的ページはHugoで、動きのあるところはフレームワークを使わないで素のPHPでやってます。で、バリデーションはVaritronがいいと噂なので使ってみました。

1. インストール

Composerのインストールは「Composerのインストール」で。

Varitronのインストールは、vendorディレクトリを配置した(したい)ディレクトリで以下を実行。他のディレクトリを汚したりしないので、気軽に実行して思ったところに配置されなかったら削除してリトライでオッケー。

composer require vlucas/valitron

2. 使用例

Contactページのバリデーションに関する部分を抜粋。

<?php

require_once(__DIR__. '/vendor/autoload.php');
Valitron\Validator::lang('ja');

$needReply  = ['Y'=>'返事が必要', 'N'=>'返事は不要'];
$messages   = [];

if ($_POST){
    $v  = new Valitron\Validator($_POST);

    $v->labels([
        'need_reply'=> '「お返事の必要有無」',
        'name_kj'   => '「お名前」',
        'email'     => '「メールアドレス」',
        'inq_msg'   => '「お問い合わせの内容」'
    ]);

    //配列にない値はNGになるので'required'はしなくてもいい
    $v->rule('in',       'need_reply', array_values($needReply));

    // $v->rule('required', ['name_kj', 'inq_msg']);と等価
    $v->rule('required', 'name_kj');
    $v->rule('required', 'inq_msg');

    if ($_POST['need_reply'] == '返事が必要'){
        $v->rule('required', 'email')->message('「返事が必要」の場合は{field}を入力してください');
    }

    //'required'すると''でも「...メールアドレスの書式として正しくありません」エラーが出る。好みじゃないので''はエラー抑止した
    if ($_POST['email']      != ''){
        $v->rule('email',    'email');
    }

    if($v->validate()) {
        // OK処理
    } else {
        $messages= $v->errors();
    }
}

/**
 * エラーメッセージを<ul><li>...</li></ul>に展開する
 * @param		string	$messages	エラーメッセージの配列
 * @return		string			    <ul><li>...</li></ul>に展開されたエラーメッセージ文字列
 */
function expandMessages($messages)
{
    if (!$messages) return '';

    $str = '<div><ul>';
    foreach ($messages as $col){
        foreach ($col as $msg){
            $str .="<li>{$msg}</li>";
        }
    }
    return $str .'</ul></div>';
}
?>

<!doctype html>
<html lang="ja">

<head>
 :
</head>

<body>

<?=expandMessages($errMessages)?>

<form method="post" name="form" novalidate>

<div>
    お返事の必要有無:
    <label for="reply_y">
        <input type="radio" value="<?=$needReply['Y']?>" name="need_reply" id="reply_y"
            <?=(!isset($_POST['need_reply']) || $_POST['need_reply']==$needReply['Y'])? 'checked': ''?>>
        <?=$needReply['Y']?>
    </label>
    <label for="reply_n">
        <input type="radio" value="<?=$needReply['N']?>" name="need_reply" id="reply_n"
            <?=( isset($_POST['need_reply']) && $_POST['need_reply']==$needReply['N'])? 'checked': ''?>>
        <?=$needReply['N']?>
    </label>
</div>

<div>
    <label for="name_kj">お名前:</label>
    <input type="text" name="name_kj" id="name_kj" value="<?=@$_POST['name_kj']?>">
</div>

<div>
    <label for="email">メールアドレス:</label>
    <input type="email" name="email" id="email" value="<?=@$_POST['email']?>" placeholder="返事が必要な場合は入力してください">
</div>

<div>
    <label for="inq_msg">お問い合わせの内容:</label>
    <textarea name="inq_msg" id="inq_msg" rows="20"><?=@$_POST['inq_msg']?></textarea>
</div>

<div>
    <input type="submit" name="submit" value="送 信">
</div>

</form>

</body>

</html>

3.その他