Introduction
Form validation
How to use
Import Fegg\Tool\Validation and create it with new. Call a check method for each field, then read the result with Validation::getErrorMessage.
<?php
namespace Site\Controller;
defined('FEGG_CORE_DIR') || exit;
use Fegg\Tool\Validation;
class Contact extends Controller
{
public function confirm()
{
$validation = new Validation();
$id = 'name';
$name = 'お名前';
$validation->required($id, $this->in($id), array('@required', $name));
$validation->maxlength($id, $this->in($id), 50, array('@maxlength', $name, 50));
$id = 'mail';
$name = 'メールアドレス';
$validation->required($id, $this->in($id), array('@required', $name));
$validation->email($id, $this->in($id), array('@email', $name));
$errorMessage = $validation->getErrorMessage();
if (!$errorMessage) {
$this->displayPage('contact/confirm');
} else {
$this->page['error'] = $errorMessage;
$this->displayPage('contact/input');
}
}
}
How checks work
- Every check method takes the field name
$namefirst. It is the key of the error message returned by Validation::getErrorMessage. - Only the first error of each field is kept: once a field has an error, the next checks of the same field are skipped and return
false. Write the checks in order of priority (e.g.requiredbeforeemail). - Except Validation::required and Validation::upload, the checks do not check an empty value (they return
true). Userequiredfor required fields. $codedecides the error message, see Configuration.
Methods
Validation::__construct
Create the validator and load the error messages
Validation::required
Check that a value is given
Validation::alphameric
Check that a value has only half-width letters and digits
Validation::numeric
Check that a value is a number
Validation::date
Check the format of a date
Validation::datetime
Check a date and time, such as the value of ``
Validation::email
Check the format of an email address
Validation::tel
Check the format of a telephone number
Validation::time
Check the format of a time
Validation::url
Check the format of a URL
Validation::zipcode
Check the format of a Japanese postal code
Validation::userid
Check the format of a user ID
Validation::password
Check the format of a password
Validation::maxbyte
Check the maximum length in bytes
Validation::length
Check the exact number of characters
Validation::maxlength
Check the maximum number of characters
Validation::minlength
Check the minimum number of characters
Validation::hankaku
Check that a value has only half-width characters
Validation::katakana
Check that a value has only katakana
Validation::upload
Check that a file was uploaded
Validation::setError
Set an error by error code
Validation::setErrorMessage
Set an error message
Validation::isError
Check whether any error was set
Validation::getErrorMessage
Get the error messages