班级清单
- App\Middleware\Cors
- App\Middleware\Auth
- App\Middleware\Env
- AppMin
- Application
- Route
- Data\Database
- Data\Db2Database
- Data\OdbcDatabase
- Data\Validator
- Data\KeyValue\SqliteStorage
- Data\Log\FileLogger
- Data\Log\HtmlLogger
- Encoding\Base64Url
- Encoding\Json
- Encoding\Utf8
- Environment\DotEnv
- Environment\System
- FileSystem\Search
- FileSystem\Security
- FileSystem\Sync
- Lang\I18N
- Lang\L10N
- Lang\Time
- Media\Image
- Net\Config
- Net\Email
- Net\HttpClient
- Net\HttpResponse
- Net\IP
- Net\SmtpClient
- Security\Crypto
- Security\Password
- Security\Crypto\Encryption
- Security\Crypto\FileEncryption
- Security\Crypto\JWT
- Security\Crypto\PublicKey
- Security\Crypto\Random
- Security\Crypto\SignedData
- Security\Web\CsrfSession
- Security\Web\CsrfStateless
- Security\Web\RateLimit
- Web\Request
- Web\Response
FastSitePHP\Data\Validator
FastSitePHP Data Validation API
For many apps validating client side (webpage or app) provides instant feedback to users and limits need for extra web request, however users can bypass validation by using DevTools or other methods so for data that needs to be validated using server-side validation is important.
This class allows for many rules to be easily defined and run against an object (or Associative Array/Dictionary).
Common rules can simply be copied from HTML Input controls.
源代码
示例代码
Validating User Input
// For many apps validating client side (webpage or app) provides instant
// feedback to users and limits need for extra web request, however users
// can bypass validation by using DevTools or other methods so for data
// that needs to be validated using server-side validation is important.
// FastSitePHP provides a class that allows for many rules to be easily
// defined and run against an object (or Associative Array/Dictionary).
// Common rules can simply be copied from HTML Input controls.
// HTML Example:
/*
<input name="name" title="Name" required>
<input name="age" title="Age" required min="13" max="99">
<input name="phone" title="Phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
*/
// FastSitePHP Code to Validate Form Post using the above HTML.
// Form Post Fields come in the PHP Superglobal array [$_POST]
// and it simply be passed to the [Validator] class.
$v = new \FastSitePHP\Data\Validator();
$v->addRules([
// Field, Title, Rules
['name', 'Name', 'required'],
['age', 'Age', 'required min="13" max="99"'],
['phone', 'Phone', 'pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"'],
]);
list($errors, $fields) = $v->validate($_POST);
if ($errors) {
// Error Logic
// [$errors] returns an array of error messages for the end user
// [$fields] returns an array of unique fields that had an error
// along with an array of error messages for each field.
// Fields can be used by a client app to highlight form fields, etc.
}
// In addition to using strings for the rules you can also use arrays.
// This can provide better performance if you have a high traffic site,
// however it runs very fast either way.
$v = new \FastSitePHP\Data\Validator();
$v->addRules([
['name', 'Name', ['required' => true]],
['age', 'Age', [
'required' => true,
'min' => '13',
'max' => '99',
]],
['phone', 'Phone', ['pattern' => '[0-9]{3}-[0-9]{3}-[0-9]{4}']],
]);
// The validator class supports a number of HTML5 rules along
// with some custom rules:
// 'exists', 'required', 'type', 'minlength', 'maxlength',
// 'length', 'min', 'max', 'pattern', 'list',
// The [type] rule supports a number of HTML5 data types along
// with many custom data types:
// 'text', 'password', 'tel', 'number', 'range', 'date',
// 'time', 'datetime', 'datetime-local', 'email', 'url',
// 'unicode-email', 'int', 'float', 'json', 'base64',
// 'base64url', 'xml', 'bool', 'timezone', 'ip', 'ipv4',
// 'ipv6', 'cidr', 'cidr-ipv4', 'cidr-ipv6',
// In addition to standard rules custom rules can be defined using
// callback functions that return true/false or a custom error
// message string:
$v
->addRules([
['site_user', 'Site User', 'check-user required'],
['site_password', 'Password', 'check-password required'],
])
->customRule('check-user', function($value) {
return ($value === 'admin');
})
->customRule('check-password', function($value) {
return ($value === 'secret' ? true : 'Invalid Password');
});
list($errors, $fields) = $v->validate($_POST);
方法
addRules(array $rules)
Add an array of rules for use with the [validation()] function in the format of [Field, Display_Name, Rules].
Field = String of the Array Key or Object Property to validate Display_Name = Field Name to include on Error Text for User - String or Null to use Field Name Rules = String of rules to be parsed or an array of defined rules
返回类型: $this
customRule($name, \Closure $callback)
Define a Custom Rule using a callback function for use with the [validation()] function.
The name must contain a dash '-' character and cannot contain spaces [ ], quotes ["], or equals [=] characters.
Examples of valid rule names:
'custom-rule'
'check-password'
'db-unique-email'
返回类型: $this
supportedRules()
Return an array of standard rules supported by this class.
返回类型: array
supportedTypes()
Return an array of types supported the [type] rule.
返回类型: array
errorText(array $error_text = null)
Get or set an Array of error message templates used when validation fails. All error text can be overridden by the calling application.
Different data types for the [type] validation can have specific messages under the 'types' option. See a full list of types in the function [supportedTypes()].
To customize text for your applications simply copy and modify the array from this function's source code.
返回类型: array | $this
validate($data)
Validate an object using rules defined from [addRules() or customRule()].
The object to validate, must be either an Associative Array (Dictionary) or an Object
Returns an array of ( error_messages[], error_fields[] ) where
error_messages[] = Error Messages to Display to End Users
error_fields[] = Dictionary with each field that had an error and an array of error messages for the field. If count(error_messages[]) = 0 then all validations passed.
返回类型: array
checkType($value, $type)
Return [true] if valid - Value matches the specified data type.
This function is marked public for validation with Unit Testing. Calling [validate()] after [addFields(), etc] is the intended use of this class.
返回类型: bool