Detailed description of Laravel framework form verification, laravel framework form
Basic verification example
Copy codeThe Code is as follows:
$ Validator = Validator: make (
Array ('name' => 'day '),
Array ('name' => 'required | min: 5 ')
);
The first parameter passed to the make function is the data to be verified, and the second parameter is the verification rule to be applied to the data.
Multiple verification rules can be separated by the "|" character or used as a separate element of the array.
Specify verification rules through Arrays
Copy codeThe Code is as follows:
$ Validator = Validator: make (
Array ('name' => 'day '),
Array ('name' => array ('requestred', 'min: 5 '))
);
Once a Validator instance is created, you can use the fails (or passes) function to perform this verification.
Copy codeThe Code is as follows:
If ($ validator-> fails ())
{
// The given data did not pass validation
}
If the verification fails, you can get the error message from the validators.
Copy codeThe Code is as follows:
$ Messages = $ validator-> messages ();
You can also use the failed function to obtain an array of unauthenticated rules without error messages.
Copy codeThe Code is as follows:
$ Failed = $ validator-> failed ();
File Verification
The Validator class provides verification rules for file verification, such as size and mimes. When you verify the file, you can pass it to the validators like other verifications.
With error message
After calling the messages function on a Validator instance, you will get a MessageBag instance, which has many convenient functions to handle error messages.
Obtains the first error message of a domain.
Copy codeThe Code is as follows:
Echo $ messages-> first ('email ');
Get all error messages for a domain
Copy codeThe Code is as follows:
Foreach ($ messages-> get ('email ') as $ message)
{
//
}
Get all error messages for all domains
Copy codeThe Code is as follows:
Foreach ($ messages-> all () as $ message)
{
//
}
Check whether a message exists in a domain
Copy codeThe Code is as follows:
If ($ messages-> has ('email '))
{
//
}
Get an error message in a certain format
Copy codeThe Code is as follows:
Echo $ messages-> first ('email ',' <p>: message </p> ');
Note: by default, messages are formatted using the Bootstrap-compatible syntax.
Get all error messages in a certain format
Copy codeThe Code is as follows:
Foreach ($ messages-> all ('<li>: message </li>') as $ message)
{
//
}
Error message & view
Once you have performed the verification, you need a simple way to feedback error messages to the view. This can be easily processed in Lavavel. The following routing is used as an example:
Copy codeThe Code is as follows:
Route: get ('register ', function ()
{
Return View: make ('user. register ');
});
Route: post ('register ', function ()
{
$ Rules = array (...);
$ Validator = Validator: make (Input: all (), $ rules );
If ($ validator-> fails ())
{
Return Redirect: to ('register ')-> withErrors ($ validator );
}
});
Note that when verification fails, we use the withErrors function to pass the Validator instance to Redirect. This function will refresh the error message stored in the Session so that it can be available in the next request.
However, note that we do not need to explicitly bind the error message to the route in the GET route. This is because Laravel always checks errors in the Session and automatically binds them to the view if they are available. Therefore, for each request, a $ errors variable is always available in all views, allowing you to conveniently think that $ errors is always defined and can be safely used. The $ errors variable is an instance of the MessageBag class.
Therefore, after the jump, you can use the automatically bound $ errors variable in the View:
Copy codeThe Code is as follows:
<? Php echo $ errors-> first ('email ');?>
Available verification rules
The following is a list of all available verification rules and their functions:
Copy codeThe Code is as follows:
Accepted
Active URL
After (Date)
Alpha
Alpha Dash
Alpha Numeric
Before (Date)
Between
Confirmed
Date
Date Format
Different
Email
Exists (Database)
Image (File)
In
Integer
IP Address
Max
MIME Types
Min
Not In
Numeric
Regular Expression
Required
Required If
Required
Required
Same
Size
Unique (Database)
Accepted
Verify that the value of this rule must be yes, on, or 1. This is useful when verifying whether you agree to the terms of service.
Active_url
Verify that the value of this rule must be a valid URL according to the PHP function checkdnsrr.
After: date
The value for verifying this rule must be passed through the PHP strtotime function after the given date.
Alpha
Verify that the value of this rule must all consist of letters.
Alpha_dash
Verify that the value of this rule must all consist of letters, numbers, dashes, or underscores.
Alpha_num
Verify that the value of this rule must all consist of letters and numbers.
Before: date
The value to verify this rule must be passed through the PHP strtotime function before the given date.
Between: min, max
The value for verifying this rule must be between the specified min and max. Strings, numbers, and files are compared using the size rules.
Confirmed
Verify that the value of this rule must be the same as that of foo_confirmation. For example, if you want to verify that the domain of this rule is password, you must have the same password_confirmation domain in the input.
Date
Verify that the value of this rule must be a valid date, according to the PHP function strtotime.
Date_format: format
Verify that the value of this rule must conform to the format specified by the PHP function date_parse_from_format.
Different: field
Verify that the value of this rule must be different from the value of the specified field.
Email
Verify that the value of this rule must be a valid email address.
Exists: table, column
Verify that the value of this rule must exist in the table of the specified database.
Basic use of Exists rules
Copy codeThe Code is as follows: 'state' => 'exists: States'
Column name
Copy codeThe Code is as follows:
'State' => 'exists: states, abbreviation'
You can also specify more conditions and add them to the query as "where.
Copy codeThe Code is as follows:
'Email '=> 'exists: staff, email, account_id, 1'
Image
Verify that the value of this rule must be an image (jpeg, png, bmp, or gif ).
In: foo, bar ,...
Verify that the value of this rule must exist in the given list.
Integer
The value of the validation rule must be an integer.
Verify that the value of this rule must be a valid IP address.
Max: value
Verify that the value of this rule must be smaller than the maximum value. Strings, numbers, and files are compared using the size rules.
Mimes: foo, bar ,...
The MIME type of the file that verifies this rule must be in the given list.
Basic use of MIME rules
Copy codeThe Code is as follows:
'Photo '=> 'mimes: jpeg, bmp, png'
Min: value
Verify that the value of this rule must be greater than the minimum value. Strings, numbers, and files are compared using the size rules.
Not_in: foo, bar ,...
The value for verifying this rule must not exist in the given list.
Numeric
Verify that the value of this rule must be a number.
Regex: pattern
Verify that the value of this rule must comply with the given regular expression.
Note: When the regex mode is used, it is necessary to use arrays to specify rules instead of pipe separators, especially when regular expressions contain a pipe character.
Required
Verify that the value of this rule must exist in the input data.
Required_if: field, value
When the specified field is a value, verify that the value of this rule must exist.
Required_with: foo, bar ,...
Verify that the value of this rule must exist only when the specified domain exists.
Required_without: foo, bar ,...
Verify that the value of this rule must exist only when the specified domain does not exist.
Same: field
Verify that the value of this rule must be the same as the value of the given domain.
Size: value
Verify that the value of this rule must be the same as the given value. For a string, value indicates the number of characters. For a number, value indicates its integer. For a file, value indicates the size of the file in KB.
Unique: table, column, partition T, idColumn
The value of the validation rule must be unique in the given database table. If column is not specified, the domain name is used.
Basic usage of Unique rules
Copy codeThe Code is as follows:
'Email '=> 'unique: users'
Column name
'Email '=> 'unique: users, email_address'
Forcibly ignore a given ID
'Email '=> 'unique: users, email_address, 10'
Url
Verify that the value of this rule must be a valid URL.
Custom error messages
If necessary, you can use custom error messages instead of default messages. There are several methods to customize error messages.
Deliver custom messages to validators
Copy codeThe Code is as follows:
$ Messages = array (
'Requestred' => 'The: attribute field is required .',
);
$ Validator = Validator: make ($ input, $ rules, $ messages );
Note: The attribute placeholder is replaced by the name of the domain to be verified. You can also use other placeholders in the error message.
Other verification placeholders
Copy codeThe Code is as follows:
$ Messages = array (
'Same' => 'The: attribute and: other must match .',
'SIZE' => 'The: attribute must be exactly: size .',
'Between' => 'The: attribute must be between: min-: max .',
'In' => 'The: attribute must be one of the following types:
: Values ',
);
In some cases, you may want to specify custom error messages for only one specified domain:
Custom error messages for a specified domain
Copy codeThe Code is as follows:
$ Messages = array (
'Email. required' => 'We need to know your e-mail address! ',
);
In some cases, you may want to specify an error message in a language file rather than directly passing it to Validator. To achieve this, add your custom messages to the custom array in the app/lang/xx/validation. php file.
Specify the error message in the language file
Copy codeThe Code is as follows:
'Custom' => array (
'Email '=> array (
'Requestred' => 'We need to know your e-mail address! ',
),
),
Custom verification rules
Laravel provides a series of useful verification rules; however, you may want to add your own verification rules. One of the methods is to use the Validator: extend function to register custom verification rules:
Register a custom verification rule
Copy codeThe Code is as follows:
Validator: extend ('foo', function ($ attribute, $ value, $ parameters)
{
Return $ value = 'foo ';
});
Note: The name of the Rule passed to the extend function must comply with the "snake cased" Naming rule.
The custom validators take three parameters: the name of the property to be verified, the value of the property to be verified, and the parameters passed to this rule.
You can also pass a class function to the extend function, instead of using the closure:
Copy codeThe Code is as follows:
Validator: extend ('foo', 'foovalidator @ validate ');
Note that you need to define error messages for your custom rules. You can either use a custom message array in the row or add it in the authentication language file.
You can also extend the Validator class, instead of using the closure callback extension validators. To achieve this, add a Validator class that inherits from Illuminate \ Validation \ Validator. You can add a verification function starting with "validate" in the class:
Extended validators class
Copy codeThe Code is as follows:
<? Php
Class CustomValidator extends Illuminate \ Validation \ Validator {
Public function validateFoo ($ attribute, $ value, $ parameters)
{
Return $ value = 'foo ';
}
}
Below, You need to register a custom authenticator extension:
You need to register a custom authenticator Extension
Copy codeThe Code is as follows:
Validator: resolver (function ($ translator, $ data, $ rules, $ messages)
{
Return new CustomValidator ($ translator, $ data, $ rules, $ messages );
});
When creating a custom verification rule, you sometimes need to define a custom placeholder for the error message. To implement it, you can create a custom validators as above and add a replaceXXX function to the validators:
Copy codeThe Code is as follows:
Protected function replaceFoo ($ message, $ attribute, $ rule, $ parameters)
{
Return str_replace (': foo', $ parameters [0], $ message );
}
How can I call multiple form verification functions in javascript?
You can write a method summary.
For example:
<Form... onSubmit = "return checkFrom ();">
Function checkFrom (){
Return method1 () & method2 () & method3 () & method4 () & method5 ()..;
}
However, it is best to sort out the verification methods to form a general verification framework.
A js Form validation framework is recommended.
In fact, jqueryValidate can be used to customize error messages. See its documentation.
The showErrors attribute can be used here:
$ (". Selector "). validate ({showErrors: function (errorMap, errorList) {$ ("# summary" ).html ("Your form contains" + this. numberOfInvalids () + "errors, see details below. "); this. defaultShowErrors ();}});
You can also refer to these attributes: errorLabelContainer, errorContainer, wrapper, errorElement, validClass, and errorClass. You only need to customize the HTML structure of the error message. You can use CSS to control the floating box.