Validation
[[toc]]
Introduction
Goravel provides several different approaches to validate your application's incoming data. It is most common to use the Validate
method available on all incoming HTTP requests. Goravel includes a wide variety of convenient validation rules.
Validation Quickstart
To learn about Goravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Goravel:
Defining The Routes
First, let's assume we have the following routes defined in our routes/web.go
file:
The GET
route will display a form for the user to create a new blog post, while the POST
route will store the new blog post in the database.
Creating The Controller
Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the Store
method empty for now:
Writing The Validation Logic
Now we are ready to fill in our Store
method with the logic to validate the new blog post.
A Note On Nested Attributes
If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax:
Form Request Validation
Creating Form Requests
For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request
Artisan CLI command:
The generated form request class will be placed in the app/http/requests
directory. If this directory does not exist, it will be created when you run the make:request
command. Each form request generated by Goravel has two methods: Authorize
, Rules
, Messages
, Attributes
and PrepareForValidation
.
As you might have guessed, the Authorize
method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the Rules
method returns the validation rules that should apply to the request's data:
So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
Note that since
form
passed values are ofstring
type by default, all fields in request should also be ofstring
type, otherwise please useJSON
to pass values.
Authorizing Form Requests
error
will be passed to the return value of ctx.Request().ValidateRequest
.
Customizing The Error Messages
You may customize the error messages used by the form request by overriding the Messages
method. This method should return an array of attribute / rule pairs and their corresponding error messages:
Customizing The Validation Attributes
Many of Goravel's built-in validation rule error messages contain an :attribute
placeholder. If you would like the :attribute
placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the Attributes
method. This method should return an array of attribute / name pairs:
Preparing Input For Validation
If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the PrepareForValidation
method:
Manually Creating Validators
If you do not want to use the Validate
method on the request, you may create a validator instance manually using the facades.Validator
. The make method on the facade generates a new validator instance:
The first argument passed to the Make
method is the data under validation that can be map[string]any
or struct
. The second argument is an array of the validation rules that should be applied to the data.
Customizing The Error Messages
If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Goravel. You may pass the custom messages as the third argument to the Make
method(also applicable to ctx.Request().Validate()
):
Specifying A Custom Message For A Given Attribute
Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule(also applicable to ctx.Request().Validate()
):
Specifying Custom Attribute Values
Many of Goravel's built-in error messages include an :attribute
placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the third argument to the Make
method(also applicable to ctx.Request().Validate()
):
Format Data Before Validation
You can format the data before validating the data for more flexible data validation, and you can pass the method of formatting the data as the third parameter to the Make
method (also applicable to ctx.Request().Validate()
):
Working With Validated Input
After validating incoming request data using form reuqests or manually created calidator instances, you still want tot bind the request data to struct
, there are two ways to do this:
Use the
Bind
methed, this will bind all incoming data, including unvalidated data:
The incoming data is automatically bound to the form when you are use request for validation:
Working With Error Messages
Retrieving one Error Message For A Field(Random)
Retrieving All Error Messages For A Field
Retrieving All Error Messages For All Fields
Determining If Messages Exist For A Field
Available Validation Rules
Below is a list of all available validation rules and their function:
required
Check value is required and cannot be empty.
required_if
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherField field is equal to any value.
required_unless
required_unless:anotherfield,value,...
The field under validation must be present and not empty unless the anotherField field is equal to any value.
required_with
required_with:foo,bar,...
The field under validation must be present and not empty only if any of the other specified fields are present.
required_with_all
required_with_all:foo,bar,...
The field under validation must be present and not empty only if all of the other specified fields are present.
required_without
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
required_without_all
required_without_all:foo,bar,...
The field under validation must be present and not empty only when all of the other specified fields are not present.
int
uint
Check value is uint(uintX)
type, value >= 0
bool
Check value is bool string(true
: "1", "on", "yes", "true", false
: "0", "off", "no", "false").
string
Check value is string type, and support size checking. eg:string
string:2
string:2,12
float
Check value is float(floatX)
type
slice
Check value is slice type([]intX
[]uintX
[]byte
[]string
)
in
in:foo,bar,…
Check if the value is in the given enumeration
not_in
not_in:foo,bar,…
Check if the value is not in the given enumeration
starts_with
starts_with:foo
Check if the input string value is starts with the given sub-string
ends_with
ends_with:foo
Check if the input string value is ends with the given sub-string
between
between:min,max
Check that the value is a number and is within the given range
max
max:value
Check value is less than or equal to the given value(intX
uintX
floatX
)
min
min:value
Check value is greater than or equal to the given value(intX
uintX
floatX
)
eq
eq:value
Check that the input value is equal to the given value
ne
ne:value
Check that the input value is not equal to the given value
lt
lt:value
Check value is less than the given value(intX
uintX
floatX
)
gt
gt:value
Check value is greater than the given value(intX
uintX
floatX
)
len
len:value
Check value length is equals to the given size(string
array
slice
map
)
min_len
min_len:value
Check the minimum length of the value is the given size(string
array
slice
map
)
max_len
max_len:value
Check the maximum length of the value is the given size(string
array
slice
map
)
email
Check value is email address string
array
Check value is array, slice type
map
Check value is a MAP type
eq_field
eq_field:field
Check that the field value is equals to the value of another field
ne_field
ne_field:field
Check that the field value is not equals to the value of another field
gt_field
gte_field:field
Check that the field value is greater than the value of another field
gte_field
gt_field:field
Check that the field value is greater than or equal to the value of another field
lt_field
lt_field:field
Check that the field value is less than the value of another field
lte_field
lte_field:field
Check if the field value is less than or equal to the value of another field
file
Verify if it is an uploaded file
image
Check if it is an uploaded image file and support suffix check
date
Check the field value is date string
gt_date
gt_date:value
Check that the input value is greater than the given date string
lt_date
lt_date:value
Check that the input value is less than the given date string
gte_date
gte_date:value
Check that the input value is greater than or equal to the given date string
lte_date
lte_date:value
Check that the input value is less than or equal to the given date string
alpha
Verify that the value contains only alphabetic characters
alpha_num
Check that only letters, numbers are included
alpha_dash
Check to include only letters, numbers, dashes ( - ), and underscores ( _ )
json
Check value is JSON string
number
Check value is number string >= 0
full_url
Check value is full URL string(must start with http,https)
ip
Check value is IP(v4 or v6) string
ipv4
Check value is IPv4 string
ipv6
Check value is IPv6 string
Custom Validation Rules
Goravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule
Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Goravel will place the new rule in the app/rules
directory. If this directory does not exist, Goravel will create it when you execute the Artisan command to create your rule:
Once the rule has been created, we are ready to define its behavior. A rule object contains two method: Passes
and Message
. This Passes
method receives the all data, data to be validated and validate parameters, it should return true
or false
based on whether the attribute value is valid. The Message
method should return the validation error message that should be used when validation fails:
Then you need to register the rule to the rules
method in the app/providers/validation_service_provider.go
file, and the rule can be used like other rules:
Points For Using Rules
int
当时用 ctx.Request().Validate(rules)
进行校验时,传入的 int
类型数据将会被 json.Unmarshal
解析为 float64
类型,从而导致 int 规则验证失败。
When using ctx.Request().Validate(rules)
for validation, the incoming int
type data will be parsed by json.Unmarshal
into float64
type, which will cause the int rule validation to fail.
Solutions
Option 2: Use facades.Validation().Make()
for rule validation;
Last updated