Crazy validation php. Validated, validated... and validated! Comparing data validators in PHP. Specifying a column name for the exists rule

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

More than 2 million domain names in service.

Promotion, domain mail, business solutions.

More than 700 thousand customers around the world have already made their choice.

*Mouse over to pause scrolling.

Back forward

Validation and data cleaning using PHP

Data security is a very important point that is often underestimated by both developers and clients. Starting with PHP 5.2.0, data cleaning and validation (checking for compliance with certain criteria) has become easier with the introduction of data filtering. Today we'll look at filtering techniques, how to use filters, and create some custom functions.

Introduction

I've always felt that writing code in PHP is easy, and it's even easier to write bad code in PHP. The widespread use of PHP in the field of web development has been facilitated by many open-source projects such as WordPress, Drupal, Magento. In addition, these are web applications like Facebook, etc. With such a widespread use of PHP (dynamic websites, blogging platforms, content management systems, use in e-commerce applications, etc.), the likelihood of encountering dirty information and insecure systems is very high. This tutorial will show some methods for cleaning and validating data using PHP. We'll focus on several input types and how to use PHP filters and custom functions.

Why clean and check?

In this guide, we will focus on information that comes directly from users, as well as from other external sources. This means that we have no control over the information we receive. All we can do is control what will be done with this information received. Almost all types of threats come from information transmitted by users or other third parties.

Among the main ones:

- XSS (Cross-Site Scripting)

This is a method of code injection where a script is injected into a page of the attacked website from a completely different site on a different server. This vulnerability is considered one of the most common on the network.

- SQL injection

The next popular vulnerability is another form of code injection, which allows for various types of malicious behavior, including unauthorized access to information, changing database information, or otherwise disrupting the normal functioning of a web application. This attack is carried out by injecting arbitrary SQL code into the request, designed to interact with the database.

- CSRF/XSRF (Cross-Site Request Forgery)

This vulnerability is less common than the previous ones. Typically, this kind of vulnerabilities arise when working with sessions and cookies, and less often when poorly verified and cleaned data. CSRF can be used to allow a site to make any requests without the user's knowledge. One of the known ways to implement this attack is to use a malformed attribute src at the picture, which leads to the execution of some script, and not to the display of the picture.

- Incorrect information

Incorrect information in itself is not a “vulnerability.” However, such information in many cases leads to a number of problems for both the site owner and the database administrator. Often, information that is incorrect in structure leads to disruptions in operation, especially if the site is implemented at an amateur level, not according to standards, as well as to failures in the operation of automated systems that expect clearly structured data in a certain format for processing.


Translation of the dialogue to the picture:

Hello, it's your son's school who are bothering you. We're having trouble with computers here.

Oh God, did he break something?

Your son's real name is Robert"); DROP TABLE students;?

Oh yes we call him Little Bobby Tables

You understand, we have lost all records for this year's students. I hope you are satisfied.

And I hope you will learn to check the information entered into the database.

For our purposes, we'll only focus on using server-side techniques to improve information security, so let's look at how the terms "sanitization" and "validation" are defined as they apply to PHP. Let's take a look at the PHP manual:

"Validation is used to check whether the information being verified meets certain requirements. For example, using FILTER_VALIDATE_EMAIL we determine whether the information is a valid (ie, structurally correct) e-mail address, but do not change this data.

Cleaning implies a possible change in the information being checked, for example, removing unwanted characters. For example, when using FILTER_SANITIZE_EMAIL, characters that should not be contained in the e-mail address will be removed. Those. In this case, there is no verification of the correctness of the address (i.e., validation), but obviously inappropriate characters are removed - nothing more."

Essentially, if you think of your site as a nightclub that everyone wants to go to, validation is the job of checking to see if a guest is on the guest list, sanitization is the bouncer that keeps unwanted elements out of the club. Like that.

What filters do I have?

All PHP installations cannot be identical. Although filters were introduced in PHP 5.2.0, not all installations have the same set of filters. In most cases, all the filters we'll talk about will already be included with PHP installed on your server, but to help you know a little more about filters, we'll look at what's available on your server specifically. The source code file is attached getfilters.php, which, once installed and running on the server, will display a list of all your filters (like the information filters available through the function filter_var, and streaming, available through stream_filter_append)

Echo "Data Filters\n

\n \n"; echo " \n"; echo " \n"; foreach(filter_list() as $id =>$filter) ( echo " \n"; ) echo "
Filter IDFilter Name
$filter".filter_id($filter)."
\n";

First we get an array containing a list of all available filters using the function filter_list, after which we loop through the array, displaying the filter name and its ID.

How do I use the filter?

PHP filters for validation and purification are activated by passing a function filter_var at least two parameters. As an example, let's apply a clearing filter on an integer:

$value = "123abc456def"; echo filter_var($value, FILTER_SANITIZE_NUMBER_INT); !}

In this example we have a variable value, which we pass to the function filter_var from the PHP Filters Extension using the FILTER_SANITIZE_NUMBER_INT filter. As a result we will get:

The cleanup filter for integers removes all non-integer characters, giving us a "clean" integer. In the sources you can try different inputs and a number of common filters will be applied to them. The archive includes various strings that you can use as test material yourself.

What do the different filters do?

The list below is not complete, but it contains most of the filters that come with a standard PHP 5.2.0+ installation.

FILTER_VALIDATE_BOOLEAN: Checks whether the passed information is a boolean value TRUE or FALSE. If the passed value is not a Boolean value, then FALSE is returned. The script below will print TRUE for the variable example value1 value02:

$value01 = TRUE; if(filter_var($value01,FILTER_VALIDATE_BOOLEAN)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = FALSE; if(filter_var($value02,FILTER_VALIDATE_BOOLEAN)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_VALIDATE_EMAIL: Checks whether the information passed is a valid e-mail address in terms of structure. It does not check whether this address actually exists, but only the validity of the address, i.e. the correctness of its structure. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(since the required part with the @ sign is missing):

$value01 = " [email protected]"; if(filter_var($value01,FILTER_VALIDATE_EMAIL)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = "nettuts"; if(filter_var($value02,FILTER_VALIDATE_EMAIL)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_VALIDATE_FLOAT: Checks whether the passed value is a floating point number. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(since split "," is not allowed in floating point numbers):

$value01 = "1.234"; if(filter_var($value01,FILTER_VALIDATE_FLOAT)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = "1.234"; if(filter_var($value02,FILTER_VALIDATE_FLOAT)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_VALIDATE_INT: Checks whether the passed value is an integer. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02(decimal numbers are not integers):

$value01 = "123456"; if(filter_var($value01,FILTER_VALIDATE_INT)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = "123.456"; if(filter_var($value02,FILTER_VALIDATE_INT)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_VALIDATE_IP: Checks if the value passed is a valid IP address. It does not check whether there is a response from this address, but only that the transferred value is, by its structure, an IP address. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02:

$value01 = "192.168.0.1"; if(filter_var($value01,FILTER_VALIDATE_IP)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = "1.2.3.4.5.6.7.8.9"; if(filter_var($value02,FILTER_VALIDATE_IP)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_VALIDATE_URL: Checks if the value passed is a valid URL. It doesn't check, it doesn't check that the resource is accessible, only that the URL structure is followed. The script below will print TRUE for the variable example value01 and FALSE for the variable example value02:

$value01 = "http://net.tutsplus.com"; if(filter_var($value01,FILTER_VALIDATE_URL)) ( echo "TRUE"; ) else ( echo "FALSE"; ) echo "

" $value02 = "nettuts"; if(filter_var($value02,FILTER_VALIDATE_URL)) ( echo "TRUE"; ) else ( echo "FALSE"; )

FILTER_SANITIZE_STRING: By default, this filter removes any invalid or unauthorized information in a string. For example, it will remove any HTML tags like or from the input string:

$value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_STRING); !}

This script will remove the tags and return the following:

Alert("TROUBLE HERE");

FILTER_SANITIZE_ENCODED: Many programmers use the function urlencode(). This filter essentially performs the same functions. For example, the following example will encode any special characters and spaces in the input string:

$value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_ENCODED); !}

The script will encode punctuation, spaces, parentheses and return the following:

%3Cscript%3Ealert%28%27TROUBLE%20HERE%27%29%3B%3C%2Fscript%3E

FILTER_SANITIZE_SPECIAL_CHARS: This filter defaults to HTML encoding of special characters such as quotes, ampersands, and parentheses. Since the demo page can't explicitly show this (since the HTML-encoded special characters will be interpreted by the browser and displayed), you can see it if you look at the source code:

$value = "alert("TROUBLE HERE");"; echo filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); !}

The special characters will be converted into their HTML entities:

FILTER_SANITIZE_EMAIL: This filter does exactly what everyone thought it would do. It removes characters from the address that should not be in the address (round and square brackets, colons, etc.) Let's say you accidentally added brackets around a letter to your address (don't ask me how, use your imagination :) )

$value = "t(e) [email protected]"; echo filter_var($value, FILTER_SANITIZE_EMAIL);

The brackets will be removed and you will receive your clean and beautiful e-mail:

[email protected]

This is an excellent filter that can be used in email forms, especially when paired with FILTER_VALIDATE_EMAIL, which will reduce user errors and prevent XSS attacks.

FILTER_SANITIZE_URL: This filter is similar to the previous one. It removes any characters that are not allowed in the URL. For example, let's say there was a "®" sign in the address by chance. Again, how he got there is a complete mystery.

$value = "http://net.tuts®plus.com"; echo filter_var($value, FILTER_SANITIZE_URL); !}

This way we will remove the unnecessary "®" sign and get a normal address:

http://net.tutsplus.com

FILTER_SANITIZE_NUMBER_INT: This filter is similar to FILTER_VALIDATE_INT, but instead of simply checking whether a number is an integer, it also removes anything that is not an integer. An excellent thing, especially against annoying spam bots and deceivers who try to enter some nonsense into the field:

$value01 = "123abc456def"; echo filter_var($value01, FILTER_SANITIZE_NUMBER_INT); echo "
"; $value02 = "1.2.3.4.5.6.7.8.9"; echo filter_var($value02, FILTER_SANITIZE_NUMBER_INT);

123456 123456789

FILTER_SANITIZE_NUMBER_FLOAT: Similar to FILTER_VALIDATE_INT. It also allows you to achieve a similar effect:

$value01 = "123abc456def"; echo filter_var($value01, FILTER_SANITIZE_NUMBER_FLOAT); echo "
"; $value02 = "1.2.3.4.5.6.7.8.9"; echo filter_var($value02, FILTER_SANITIZE_NUMBER_FLOAT);

Both sets of characters are converted and the output is the following:

123456 123456789

$value = "1.23"; echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT);

The point will be removed and the value returned:

One of the main reasons that the FILTER_SANITIZE_NUMBER_FLOAT and FILTER_SANITIZE_INT filters are separated is the ability to use the special flag FILTER_FLAG_ALLOW_FRACTION, which comes as the third parameter passed to the function filter_var:

$value = "1.23"; echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

Options, flags and control arrays - Mein Gott!

The flag used in the previous example is just one way to gain more granular control over the types of data that will be cleaned, delimiter definitions, how arrays are processed by filters, etc. You can learn more about the flags and functions used in connection with the use of filters in the PHP manual, in the part dedicated to Filters - php.net/manual/en/book.filter.php.

Other methods for clearing information using PHP

We'll now look at a few key data scrubbing techniques to prevent an attack on your application. They are especially relevant for those applications that still run on PHP4, as they appeared with its release.

htmlspecialchars: This PHP function converts 5 special characters into corresponding HTML entities.

The following are subject to transformation:

& (ampersand)
" (double quotes) when the ENT_NOQUOTES flag is not set
’ (single quotes) only when the ENT_QUOTES flag is set
< (меньше, чем)
> (more than)

This function is used in the same way as any other in PHP:

Echo htmlspecialchars("$string");

htmlentities: Similar to a function htmlspecialchars this function converts special characters to their HTML entities. The only difference is that in this case all special characters that can be converted are converted. This is a fairly common method for obfuscating e-mail addresses from spam bots, since not all of them are configured to read html entities:

Echo htmlentities("$string");

mysql_real_escape_string: This is a MySQL feature that helps protect against SQL injection attacks. It is considered good practice (and in fact a necessity) to pass all information passed to the SQL query through this function. It escapes all dangerous special characters that can cause problems and cause little Bobby Tables will destroy another table in the school database.

$query = "SELECT * FROM table WHERE value=".mysql_real_escape_string("$string")." LIMIT 1,1"; $runQuery = mysql_query($query); !}

Custom Functions

For many people, the built-in features and filters may not be enough. Often more stringent and narrower validation or purification may be required. To achieve the desired results, many people write functions for data validation themselves. An example is the option of searching a database for values ​​of a certain type, like:

Function checkZipCode($value) ( ​​$zipcheck = "SELECT COUNT(*) FROM `database`.`zipcodes` WHERE value="".filter_var(mysql_real_escape_string($value),FILTER_SANITIZE_NUMBER_INT)."""; $count = mysql_query( $zipcheck); if($count==1) ( return TRUE; ) else ( return FALSE; ) )

Other user functions may not be directly connected to the database, but prepare information before inserting it into the database:

Function cleanString($string) ( $detagged = strip_tags($string); if(get_magic_quotes_gpc()) ( $stripped = stripslashes($detagged); $escaped = mysql_real_escape_string($stripped); ) else ( $escaped = mysql_real_escape_string($ detagged); ) return $escaped; )

The possibilities are almost endless, especially when using regular expressions. However, for most cases, the use of filters can already solve the necessary problems.

Did you like the material and want to thank me?
Just share with your friends and colleagues!


Laravel comes with a simple, user-friendly system for validating (checking input data against rules) and receiving error messages - the Validation class.

The simplest example of validation $validator = Validator::make(array("name" => "Dale"), array("name" => "required|min:5"));

The first parameter passed to the make method is the data to be tested. The second parameter is the rules that should be applied to them.

Using Arrays to Specify Rules

Multiple rules can be separated either by a straight line (|) or be individual array elements.

$validator = Validator::make(array("name" => "Dale"), array("name" => array("required", "min:5")));

Validating multiple fields $validator = Validator::make(array("name" => "Dale", "password" => "badpassword", "email" => " [email protected]"), array("name" => "required", "password" => "required|min:8", "email" => "required|email|unique"));

Once a Validator instance has been created, the fails (or passes) method can be used to perform the validation.

If ($validator->fails()) ( // Transmitted data failed verification)

If the Validator finds errors, you can get its messages like this:

$messages = $validator->messages();

You can also get an array of rules, data that failed verification, without the messages themselves:

$failed = $validator->failed();

Checking files

The Validator class contains several initial rules for validating files, such as size , mimes and others. To perform checks on files, simply transfer the files along with other data.

Hook after validation

After completion of validation, Laravel can run your closure function, in which you can, for example, check something special or add some kind of error message. The after() method is used for this:

$validator = Validator::make(...); $validator->after(function($validator) ( if ($this->somethingElseIsInvalid()) ( $validator->errors()->add("field", "Something is wrong with this field!"); ) )); if ($validator->fails()) ( // )

You can add multiple afters if needed.

Validation in controllers

Writing complete validation code every time you need to validate data is inconvenient. Therefore, Laravel provides several solutions to simplify this procedure.

The base App\Http\Controllers\Controller controller includes the ValidatesRequests trait, which already contains methods for validation:

/** * Save the blog post. * * @param Request $request * @return Response */ public function store(Request $request) ( $this->validate($request, [ "title" => "required|unique|max:255", "body" => "required", ]); // )

If validation passes, the code continues to execute. If not, an Illuminate\Contracts\Validation\ValidationException is thrown. If you don't catch this exception, the framework will catch it, fill the flash variables with validation error messages and redirect the user to the previous page with the form - itself!

In the case of an AJAX request, the redirect does not occur; the framework returns a response with HTTP code 422 and JSON with validation errors.

The code above is similar to this:

/** * Save the blog post. * * @param Request $request * @return Response */ public function store(Request $request) ( $v = Validator::make($request->all(), [ "title" => "required|unique|max :255", "body" => "required", ]); if ($v->fails()) ( return redirect()->back()->withErrors($v->errors()); ) // )

Error Format Changes

If you want to customize the validation error messages that are stored in session flash variables during a redirect, override the formatValidationErrors method in your controller:

/** * (@inheritdoc) */ protected function formatValidationErrors(\Illuminate\Validation\Validator $validator) ( return $validator->errors()->all(); ) Query validation

To implement more complex validation scenarios, you may find it convenient to use the so-called Form Requests. These are special HTTP request classes that contain validation logic. They process the request before it reaches the controller.

To create a request class, use the make:request artisan command:

Php artisan make:request StoreBlogPostRequest

The class will be created in the app/Http/Requests folder. Add the necessary validation rules to its rules method:

/** * Get the validation rules that apply to the request. * * @return array */ public function rules() ( return [ "title" => "required|unique|max:255", "body" => "required", ]; )

In order for the framework to intercept the request before the controller, add this class to the arguments of the required controller method:

With proper use of query validation, you can be sure that your controllers always contain only validated input data!

In case of unsuccessful validation, the framework fills the flash variables with validation errors and returns a redirect to the previous page. In the case of an AJAX request, a response with code 422 and JSON with validation errors is returned.

Access control

Form Request classes also contain an authorize method. In this method, you can check if the user is allowed to perform this action, update a given resource. For example, if a user tries to edit a comment on a post, are they the author?

/** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() ( $commentId = $this->route("comment"); return Comment::where("id", $commentId) ->where("user_id", Auth: :id())->exists(); )

Notice the route() method call above. This method gives you access to the parameters in the url (in this case (comment)) defined in the route:

Route::post("comment/(comment)");

If the authorize method returns false, the framework generates a response with HTTP code 403 and sends it immediately. The controller method is not executed.

/** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() ( return true; )

Error Format Changes in Flash Variables

If you want to customize the validation error messages that are stored in session flash variables during a redirect, override the formatValidationErrors method in the base request class (App\Http\Requests\Request):

/** * (@inheritdoc) */ protected function formatValidationErrors(\Illuminate\Validation\Validator $validator) ( return $validator->errors()->all(); ) Working with error messages

After calling the messages method of the Validator object, you will receive a MessageBag object, which has a set of useful methods for accessing error messages.

Getting the first message for the field echo $messages->first("email"); Getting all messages for one field foreach ($messages->get("email") as $message) ( // ) Getting all messages for all fields foreach ($messages->all() as $message) ( // ) Validation for the presence of a message for the field if ($messages->has("email")) ( // ) Receiving an error in the specified format echo $messages->first("email", "");

Note: By default, posts are formatted to fit Twitter Bootstrap.

Retrieving all messages in a given format foreach ($messages->all("
  • :message
  • ") as $message) ( // ) Errors and patterns

    Once you've done your validation, you'll need a simple way to pass errors to the template. Laravel makes this easy to do. For example, we have the following routes:

    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("register")->withErrors($validator); ) ));

    Note that when the checks fail, we pass the Validator object to the Redirect object using the withErrors method. This method will store error messages in one-time session flash variables, thus making them available for the next request.

    However, note that we are not passing View::make("user.register"); $errors variables to the template. Laravel itself checks the session data for the presence of variables and automatically passes them to the template if they are available. Thus, it is important to remember that the $errors variable will be available to all your templates at all times, on any request. . This allows you to assume that the $errors variable is always defined and can be safely used. The $errors variable is an instance of the MessageBag class.

    So, after the redirect, you can use the $errors variable automatically set in the template:

    Named MessageBag

    If you have several forms on the page, then you can select the name of the MessageBag object in which error texts will be returned so that you can display them correctly for the desired form.

    Return redirect("register")->withErrors($validator, "login");

    Get error text from MessageBag with name login:

    Validation Rules

    Below is a list of all available rules and their functions:

    accepted

    The field must be in value yes, on or 1 . This is useful for checking acceptance of rules and licenses.

    active_url

    The field must be a valid URL, accessible through the checkdnsrr function.

    after: date

    The field must be a date later than date

    alpha

    The field must contain only alphabetic characters.

    alpha_dash

    The field must contain only alphabetic characters, numbers, underscores (_), and hyphens (-).

    alpha_num

    The field must contain only alphabetic characters and numbers.

    array

    The field must be an array.

    before: date

    The field must be a date earlier than date. Strings are converted to dates using the strtotime function.

    between: min,max

    The field must have a size ranging from min before max. Strings, numbers, and files are treated similarly to the size rule.

    boolean

    The field must be Boolean. Allowed values ​​are true , false , 1 , 0 , "1" and "0" .

    confirmed

    The value of the field must match the value of the field with that name, plus foo_confirmation . For example, if the password field is checked, then the password_confirmation field that matches the value must be passed to the input.

    date

    The field must be a valid date according to the strtotime function.

    date_format: format

    The field must match the date format format according to the date_parse_from_format function.

    different: field

    The value of the field being checked must be different from the value of the field field.

    email

    The field must be a valid email address.

    exists: table,column

    The field must exist in the specified database table.

    Easy to use:

    "state" => "exists:states"

    Specifying a field name in a table:

    "state" => "exists:states,abbreviation"

    You can also specify more conditions to be added to the "WHERE" query:

    "email" => "exists:staff,email,account_id,1"

    image

    The uploaded file must be an image in jpeg, png, bmp, gif or svg format.

    in: foo,bar,...

    The field value must be one of the following ( foo, bar etc.).

    integer

    The field must have a valid integer value.

    ip

    The field must be a valid IP address.

    max: value

    The field value must be less than or equal to value

    mimes: foo,bar,...

    The MIME type of the uploaded file must be one of the listed ones.

    Easy to use:

    "photo" => "mimes:jpeg,bmp,png"

    min: value

    The field value must be more than value. Strings, numbers and files are treated similarly to the rule.

    not_in: foo,bar,...

    The field value must not be one of the following ( foo, bar etc.).

    numeric

    The field must have a valid numeric or fractional value.

    regex: pattern

    The field must match the given regular expression.

    Warning: When using this rule, you may need to list other rules as array elements, especially if the expression contains the pipe character (|).

    required

    The field being tested must be present and have a non-empty value.

    required_if: field,value,...

    The field being tested must be present and have a non-empty value if the other field field present and has any of the meanings value.

    required_with: foo,bar,...

    At least one of the listed fields is present and has a non-empty value ( foo, bar etc.).

    required_with_all: foo,bar,...

    The field being tested must be present and have a non-empty value, but only if all of the fields listed are present and have a non-empty value ( foo, bar etc.).

    required_without: foo,bar,...

    The field being checked must be present and have a non-empty value, but only if at least one of the listed fields is not present or has an empty value ( foo, bar etc.).

    required_without_all: foo,bar,...

    The field being checked must be present and have a non-empty value, but only if all of the listed fields are not present or have empty values ​​( foo, bar etc.).

    same: field

    The field must have the same value as the field field.

    size: value

    The field must match value size. For strings this is the length, for numbers it is the number, for files it is the size in kilobytes.

    timezone

    The field must contain a time zone identifier, one of those listed in the timezone_identifiers_list php function

    unique: table,column,except,idColumn

    The field value must be unique in the given database table. If column is not specified, the field name will be used.

    Simple use "email" => "unique:users" Specifying a field name in the table "email" => "unique:users,email_address" Ignoring a specific ID "email" => "unique:users,email_address,10" Adding additional conditions

    You can also specify more conditions to be added to the "WHERE" query:

    "email" => "unique:users,email_address,NULL,id,account_id,1"

    In the rule above, only rows with account_id equal to 1 will be included in the check.

    url

    The field must be a valid URL.

    Note: PHP function filter_var is used

    Conditional rules

    Sometimes you need to validate a certain field only when it is present in the input data. To do this, add the sometimes rule:

    $v = Validator::make($data, array("email" => "sometimes|required|email",));

    In the example above, the email field will only trigger validation when $data["email"] exists.

    Complex conditional rules

    Sometimes you only want a field to have a value if another field has a value, say, greater than 100. Or you may only require two fields to have a value when a third one is also specified. This is easily achieved by conditional rules. First create a Validator object with a set of static rules that never change:

    $v = Validator::make($data, array("email" => "required|email", "games" => "required|numeric",));

    Now let's say your application is written for game collectors. If a collector with more than 100 games registers, then we want to ask them why they need that many. For example, they may have a store or maybe they just like to collect them. So, to add such a conditional rule, we use the Validator method.

    $v->sometimes("reason", "required|max:500", function($input) ( return $input->games >= 100; ));

    The first parameter of this method is the name of the field we are checking. The second parameter is the rule we want to add if the passed closure function (third parameter) returns true . This method allows you to easily create complex input validation rules. You can even add the same conditional rules to multiple fields at the same time:

    $v->sometimes(array("reason", "cost"), "required", function($input) ( return $input->games >= 100; ));

    Note: The $input parameter passed to the closure is an Illuminate\Support\Fluent object and can be used to read the input and files being inspected.

    Own error messages

    You can pass your own error messages instead of the default ones. There are several ways to do this.

    Passing your messages to Validator $messages = array("required" => "Field:attribute must be filled in.",); $validator = Validator::make($input, $rules, $messages);

    Note: the line:attribute will be replaced with the name of the field being checked. You can also use other variable strings.

    Using other string variables $messages = array("same" => "The values ​​of:attribute and:other must match.", "size" => "The field:attribute must be exactly:size.", "between" => "The value of:attribute must be from:min to:max.", "in" => "The field:attribute must have one of the following values: :values",); Specifying your own message for a specific field

    Sometimes you may need to specify your message for a separate field.

    $messages = array("email.required" => "We need to know your email address!",);

    Specifying your own messages in the localization file

    It is also possible to define validation messages in the localization file instead of passing them to Validator directly. To do this, add messages to the custom array of the localization file app/lang/xx/validation.php.

    "custom" => array("email" => array("required" => "We need to know your email address!",),),

    Own validation rules Register your own validation rule

    Laravel comes with a lot of useful rules out of the box, but you may need to create your own. One way to register a custom rule is through the Validator::extend method.

    Validator::extend("foo", function($attribute, $value, $parameters) ( return $value == "foo"; }); !}

    Note: The rule name must be in the format_with_underscores.

    The passed closure function receives three parameters: the name of the field being checked $attribute , the value of the field $value and the array of parameters $parameters passed to the rule.

    Instead of a function, you can pass a reference to a class method to the extend method:

    Validator::extend("foo", "FooValidator@validate");

    Note that you will also need to define an error message for the new rule. You can do this either by passing it as an array of strings to the Validator, or by writing it into a localization file.

    Extending the Validator class

    Instead of using closure functions to extend the set of available rules, you can extend the Validator class itself. To do this, create a class that inherits Illuminate\Validation\Validator . You can add new validation methods by starting their name with validate .

    Share with friends or save for yourself:

    Loading...