pub struct Rule(/* private fields */);Expand description
A built-in or custom input validation rule.
Build rules with the constructors, such as Rule::required and Rule::max_length.
Each #[validate(..)] attribute has a constructor of the same name. Where an attribute takes a
list of values, the constructor takes an array. These constructors differ from their
attributes:
decimal(2, 4)isRule::decimal_between.- A bare
urlisRule::url(["http", "https"]), and a bareuuidisRule::uuid(None). Rule::regex,Rule::not_regex, andRule::date_formatreturn aResult, because a pattern can be invalid. The attributes check their patterns at compile time.- With a table name,
exists("categories", "id")isRule::exists_in::<i64>("categories", "id"), which names the field’s type, andunique("posts", "slug")isRule::unique_in::<String>("posts", "slug").
use laravel::validation::{Rule, Rules};
let rules = Rules::new()
.field("username", [Rule::required(), Rule::ascii(), Rule::alpha_dash(), Rule::min_length(3)])
.field("terms", [Rule::accepted()])
.nullable("address")
.field("address", [Rule::required_unless("delivery", "pickup")])
.field("delivery", [Rule::one_of(["ship", "pickup"])]);Implementations§
Source§impl Rule
impl Rule
Sourcepub const fn bail() -> Rule
pub const fn bail() -> Rule
Stops validating this field and its children after the field’s first failed rule. The rule takes effect wherever it appears in the field’s rule list.
Sourcepub const fn string() -> Rule
pub const fn string() -> Rule
Requires a string without converting numbers or booleans to text.
Sourcepub const fn min_length(min: usize) -> Rule
pub const fn min_length(min: usize) -> Rule
Requires at least this many Unicode scalar values in a string.
Sourcepub const fn max_length(max: usize) -> Rule
pub const fn max_length(max: usize) -> Rule
Allows at most this many Unicode scalar values in a string.
Sourcepub fn one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires a scalar whose text representation is one of these choices.
Sourcepub fn not_one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn not_one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Rejects scalars whose text representation is one of these choices.
Sourcepub const fn confirmed() -> Rule
pub const fn confirmed() -> Rule
Requires the same submitted value in <name>_confirmation, such as password_confirmation
for password. The values compare without converting types.
Sourcepub fn same(field: impl Into<String>) -> Rule
pub fn same(field: impl Into<String>) -> Rule
Requires the same submitted value as another field, compared without converting types, so
1 and "1" differ. A missing field counts as null.
Sourcepub fn different(field: impl Into<String>) -> Rule
pub fn different(field: impl Into<String>) -> Rule
Requires a different submitted value from another field. The rule passes when the other field is missing.
Sourcepub const fn alpha() -> Rule
pub const fn alpha() -> Rule
Requires a string containing only Unicode letters and combining marks.
Sourcepub const fn alpha_num() -> Rule
pub const fn alpha_num() -> Rule
Requires a string or number made of Unicode letters, marks, or numbers.
Sourcepub const fn alpha_dash() -> Rule
pub const fn alpha_dash() -> Rule
Requires a string or number made of Unicode letters, marks, numbers, dashes, or underscores.
Sourcepub const fn ascii() -> Rule
pub const fn ascii() -> Rule
Requires a string containing only ASCII characters, including control characters.
Sourcepub fn starts_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn starts_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires a string that starts with one of these prefixes.
Sourcepub fn ends_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn ends_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires a string that ends with one of these suffixes.
Sourcepub fn doesnt_start_with(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn doesnt_start_with( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Rejects a string that starts with one of these prefixes.
Sourcepub fn doesnt_end_with(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn doesnt_end_with( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Rejects a string that ends with one of these suffixes.
Sourcepub const fn digits(count: usize) -> Rule
pub const fn digits(count: usize) -> Rule
Requires exactly this many ASCII digits.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("pin", [Rule::digits(4)]);Sourcepub const fn digits_between(min: usize, max: usize) -> Rule
pub const fn digits_between(min: usize, max: usize) -> Rule
Requires a number of ASCII digits from min through max. A reversed range fails
validation.
Sourcepub const fn min_digits(min: usize) -> Rule
pub const fn min_digits(min: usize) -> Rule
Requires at least this many ASCII digits.
Sourcepub const fn max_digits(max: usize) -> Rule
pub const fn max_digits(max: usize) -> Rule
Allows at most this many ASCII digits.
Sourcepub fn min_value(min: impl Into<Number>) -> Rule
pub fn min_value(min: impl Into<Number>) -> Rule
Requires a number greater than or equal to min. The value may be a JSON number or a
numeric string. Any other value fails with the numeric message.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("quantity", [Rule::min_value(1)]);Sourcepub fn max_value(max: impl Into<Number>) -> Rule
pub fn max_value(max: impl Into<Number>) -> Rule
Requires a number less than or equal to max. The value may be a JSON number or a numeric
string. Any other value fails with the numeric message.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("count", [Rule::max_value(u64::MAX)]);Sourcepub fn between(min: impl Into<Number>, max: impl Into<Number>) -> Rule
pub fn between(min: impl Into<Number>, max: impl Into<Number>) -> Rule
Requires a number from min through max.
The value may be a JSON number or a numeric string, as for Rule::min_value. A reversed
interval or a NaN or infinite bound fails validation instead of panicking.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("rating", [Rule::between(0.0, 5.0)]);Sourcepub fn gt(field: impl Into<String>) -> Rule
pub fn gt(field: impl Into<String>) -> Rule
Requires a number greater than another submitted field.
The other field’s name resolves relative to the current object. The comparison fails when
the other field is missing, null, or not numeric. A value that isn’t numeric fails with the
numeric message. Both values compare by their submitted decimal digits, without rounding.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("maximum", [Rule::gt("minimum")]);Sourcepub fn gte(field: impl Into<String>) -> Rule
pub fn gte(field: impl Into<String>) -> Rule
Requires a number greater than or equal to another submitted field.
The other field resolves and compares as for Rule::gt.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("maximum", [Rule::gte("minimum")]);Sourcepub fn lt(field: impl Into<String>) -> Rule
pub fn lt(field: impl Into<String>) -> Rule
Requires a number less than another submitted field.
The other field resolves and compares as for Rule::gt.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("discount", [Rule::lt("price")]);Sourcepub fn lte(field: impl Into<String>) -> Rule
pub fn lte(field: impl Into<String>) -> Rule
Requires a number less than or equal to another submitted field.
The other field resolves and compares as for Rule::gt.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("discount", [Rule::lte("price")]);Sourcepub const fn decimal(places: usize) -> Rule
pub const fn decimal(places: usize) -> Rule
Requires exactly this many written decimal places in a numeric value.
A numeric string keeps its trailing zeros, so "1.50" has two places. A leading sign is
allowed, and scientific notation fails. A JSON number counts the places of its decoded
value. The rule doesn’t change the input.
use laravel::validation::{Rule, Rules, Validate};
#[derive(serde::Deserialize, Validate)]
struct Product {
#[validate(required, decimal(2))]
price: String,
}
let rules = Rules::new().field("price", [Rule::decimal(2)]);Sourcepub const fn decimal_between(min: usize, max: usize) -> Rule
pub const fn decimal_between(min: usize, max: usize) -> Rule
Requires a number of written decimal places from min through max. A reversed range fails
validation.
The rule counts places as Rule::decimal does.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("measurement", [Rule::decimal_between(2, 4)]);Sourcepub fn multiple_of(divisor: impl Into<Number>) -> Rule
pub fn multiple_of(divisor: impl Into<Number>) -> Rule
Requires an exact multiple of divisor. The rule compares decimal digits, so it doesn’t
suffer floating-point rounding: "0.30" is a multiple of 0.01.
A divisor may be negative. A zero, NaN, or infinite divisor fails validation instead of panicking. An input of zero is a multiple of every finite, nonzero divisor.
use laravel::validation::{Rule, Rules};
use serde_json::json;
let rules = Rules::new().field("price", [Rule::multiple_of(0.01)]);
let input = serde_json::from_value(json!({ "price": "0.30" }))?;
assert!(rules.validate(&input).await.is_ok());Sourcepub const fn date() -> Rule
pub const fn date() -> Rule
Requires a real calendar date in YYYY-MM-DD, with a year from 0001 through 9999.
The rule checks the submitted text, which serde can then decode into a
civil::Date.
use laravel::validation::{Rule, Rules, Validate};
#[derive(serde::Deserialize, Validate)]
struct Booking {
#[validate(required, date)]
starts_on: laravel::time::civil::Date,
}
let rules = Rules::new().field("starts_on", [Rule::required(), Rule::date()]);Sourcepub const fn datetime() -> Rule
pub const fn datetime() -> Rule
Requires an RFC 3339 timestamp with seconds and an explicit UTC offset.
The rule accepts four-digit years and up to nine digits of fractional seconds, within the
range of a Timestamp. It rejects leap seconds. Serde can decode
the text into a Timestamp.
use laravel::validation::{Rule, Rules, Validate};
#[derive(serde::Deserialize, Validate)]
struct Appointment {
#[validate(required, datetime)]
starts_at: laravel::time::Timestamp,
}
let rules = Rules::new().field("starts_at", [Rule::required(), Rule::datetime()]);Sourcepub fn date_format(
formats: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Rule, Error>
pub fn date_format( formats: impl IntoIterator<Item = impl Into<String>>, ) -> Result<Rule, Error>
Requires submitted text that matches one of these strftime formats exactly, such as
%d/%m/%Y.
Each format must describe a complete calendar date, or a time of day that includes the
hour. The rule checks that the date and time are real, then checks that formatting them
again reproduces the submitted text. These formats don’t change how serde decodes the field,
so decode it as a String and parse it in the handler.
§Errors
Returns an error when the list is empty, or when a format has an invalid directive,
describes an incomplete date, or can’t be parsed, such as one with a timezone abbreviation
(%Z).
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("birthday", [Rule::date_format(["%d/%m/%Y", "%Y-%m-%d"])?]);Sourcepub const fn timezone() -> Rule
pub const fn timezone() -> Rule
Requires an IANA timezone name, such as America/Chicago. The rule looks the name up in the
system’s timezone database, or in a bundled copy when the system has none. It accepts
aliases and UTC, and rejects numeric offsets and POSIX timezone expressions.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("timezone", [Rule::required(), Rule::timezone()]);Sourcepub fn after(field: impl Into<String>) -> Rule
pub fn after(field: impl Into<String>) -> Rule
Requires a date or timestamp after another submitted field of the same kind.
Both values must be calendar dates that Rule::date accepts, or timestamps that
Rule::datetime accepts. Timestamps compare as instants, to the nanosecond. Comparing a
calendar date with a timestamp fails. A value that’s neither fails with the date message.
The argument always names a field, never a literal date, and resolves relative to the current object. The comparison fails when the other field is missing, null, or malformed.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("ends_on", [Rule::after("starts_on")]);Sourcepub fn after_or_equal(field: impl Into<String>) -> Rule
pub fn after_or_equal(field: impl Into<String>) -> Rule
Requires a date or timestamp on or after another submitted field of the same kind.
The values parse and the other field resolves as for Rule::after.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("ends_on", [Rule::after_or_equal("starts_on")]);Sourcepub const fn after_today() -> Rule
pub const fn after_today() -> Rule
Requires a date after today. Today is the current date in UTC, as
laravel::time::today returns it. A timestamp that
Rule::datetime accepts compares by its date in UTC. A value that’s neither a date nor a
timestamp fails with the date message.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("starts_on", [Rule::after_today()]);Sourcepub const fn today_or_after() -> Rule
pub const fn today_or_after() -> Rule
Requires today’s date or a later one, compared as Rule::after_today compares.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("starts_on", [Rule::today_or_after()]);Sourcepub const fn before_today() -> Rule
pub const fn before_today() -> Rule
Requires a date before today, compared as Rule::after_today compares.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("born_on", [Rule::before_today()]);Sourcepub const fn today_or_before() -> Rule
pub const fn today_or_before() -> Rule
Requires today’s date or an earlier one, compared as Rule::after_today compares.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("paid_on", [Rule::today_or_before()]);Sourcepub fn before(field: impl Into<String>) -> Rule
pub fn before(field: impl Into<String>) -> Rule
Requires a date or timestamp before another submitted field of the same kind.
The values parse and the other field resolves as for Rule::after.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("starts_on", [Rule::before("ends_on")]);Sourcepub fn before_or_equal(field: impl Into<String>) -> Rule
pub fn before_or_equal(field: impl Into<String>) -> Rule
Requires a date or timestamp on or before another submitted field of the same kind.
The values parse and the other field resolves as for Rule::after.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("starts_on", [Rule::before_or_equal("ends_on")]);Sourcepub fn date_equals(field: impl Into<String>) -> Rule
pub fn date_equals(field: impl Into<String>) -> Rule
Requires a date or timestamp equal to another submitted field of the same kind.
The other field resolves as for Rule::after. The comparison fails when the other field
is missing or malformed, or when one value is a date and the other a timestamp.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("confirmed_at", [Rule::date_equals("starts_at")]);Sourcepub const fn email() -> Rule
pub const fn email() -> Rule
Requires a single email address, including international local parts and domains.
The rule rejects display names, comments, domain literals, and control characters. The local part may be up to 64 UTF-8 bytes. The full address may be up to 254 bytes after the rule converts its domain to ASCII for checking. The rule doesn’t change the input.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("email", [Rule::required(), Rule::email()]);Sourcepub fn url(schemes: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn url(schemes: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires an absolute URL with a host and one of these schemes.
Schemes compare without regard to case. An empty list accepts no URLs. The rule doesn’t change the submitted string or repair malformed syntax.
use laravel::validation::{Rule, Rules};
let rules = Rules::new()
.field("website", [Rule::url(["http", "https"])])
.field("callback", [Rule::url(["https"])]);Sourcepub fn uuid(version: impl Into<Option<u8>>) -> Rule
pub fn uuid(version: impl Into<Option<u8>>) -> Rule
Requires a UUID in canonical form, of this version. Pass a version from 1 through 8, or 0
for the nil UUID. None accepts any version, including the nil and max UUIDs. Any other
version number fails validation instead of panicking.
use laravel::validation::{Rule, Rules, Validate};
#[derive(serde::Deserialize, Validate)]
struct Account {
#[validate(required, uuid = 7)]
id: uuid::Uuid,
}
let rules = Rules::new()
.field("id", [Rule::required(), Rule::uuid(7)])
.field("parent_id", [Rule::uuid(None)]);Sourcepub const fn mac_address() -> Rule
pub const fn mac_address() -> Rule
Requires a MAC address whose groups are separated by colons, hyphens, or dots.
Sourcepub const fn json() -> Rule
pub const fn json() -> Rule
Requires a string that holds valid JSON, including a scalar such as null or 12.
Sourcepub fn regex(pattern: impl AsRef<str>) -> Result<Rule, Error>
pub fn regex(pattern: impl AsRef<str>) -> Result<Rule, Error>
Compiles a regex that a submitted string or number must match.
The pattern may match anywhere in the text, so use anchors such as \A and \z to match
the whole value. To reuse the compiled pattern, keep the rule or clone it.
§Errors
Returns the regex compilation error when the pattern is invalid or unsupported.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("code", [Rule::regex(r"\A[A-Z]{3}-[0-9]{4}\z")?]);In a derive attribute, an invalid pattern fails to compile:
#[derive(laravel::validation::Validate)]
struct Coupon {
#[validate(regex = "[")]
code: String,
}Sourcepub fn not_regex(pattern: impl AsRef<str>) -> Result<Rule, Error>
pub fn not_regex(pattern: impl AsRef<str>) -> Result<Rule, Error>
Compiles a regex that a submitted string or number must not match. A value that’s neither a string nor a number fails, even though the pattern doesn’t match it.
§Errors
Returns the regex compilation error when the pattern is invalid or unsupported.
use laravel::validation::Rule;
let rule = Rule::not_regex(r"(?i)admin|root")?;Sourcepub const fn required() -> Rule
pub const fn required() -> Rule
Requires a value that is present, not null, and not empty. Zero and false pass.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("name", [Rule::required(), Rule::string(), Rule::max_length(100)]);Sourcepub const fn filled() -> Rule
pub const fn filled() -> Rule
Requires a nonempty value when the field is submitted. The rule passes when the field is missing.
Sourcepub const fn present() -> Rule
pub const fn present() -> Rule
Requires the field to be submitted. A submitted null or empty value passes.
Sourcepub const fn prohibited() -> Rule
pub const fn prohibited() -> Rule
Requires the field to be missing or empty.
Sourcepub const fn current_password() -> Rule
pub const fn current_password() -> Rule
Requires the logged-in user’s password, such as on a form that changes it. Guests fail.
The rule checks the session guard’s user, so it reads the request. Validate input with this
rule through Valid, Request::validate,
or Request::validate_with.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("current_password", [Rule::required(), Rule::current_password()]);Sourcepub const fn password() -> Rule
pub const fn password() -> Rule
Requires a password that meets the application’s PasswordRule, such
as at least 8 characters with a number. A value that misses several requirements gets a
message for each one.
For other requirements on one field, convert a PasswordRule instead, as in
Rule::from(PasswordRule::min(12).symbols()).
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("password", [Rule::required(), Rule::password(), Rule::confirmed()]);Sourcepub const fn file() -> Rule
pub const fn file() -> Rule
Requires an uploaded file.
The file rules check the files that the request uploaded under the field’s name. For a list
such as photos[], every file must pass. An uploaded file counts as a value for
Rule::required and the other presence rules.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("resume", [Rule::required(), Rule::file(), Rule::max_kilobytes(5120)]);Sourcepub const fn image() -> Rule
pub const fn image() -> Rule
Requires an uploaded JPEG, PNG, GIF, BMP, or WebP image. The rule reads the file’s content, not its name. It rejects SVG, because an SVG file can carry scripts.
Sourcepub fn mimes(types: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn mimes(types: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires an uploaded file whose content is one of these types.
Name each type by its extension, such as pdf or zip, by its MIME type, such as
application/pdf, or by a family of MIME types, such as video/*. Names ignore case, and
jpg and jpeg name the same format. The rule reads the file’s content, not its name, so
it can’t recognize formats without a signature, such as plain text or CSV. Use
Rule::extensions for those formats.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("attachment", [Rule::required(), Rule::mimes(["pdf", "image/*"])]);Sourcepub fn extensions(
extensions: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn extensions( extensions: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires an uploaded file whose name on the user’s computer ends with one of these
extensions, in any case. The user chooses the file’s name, so pair this rule with
Rule::mimes when the format has a signature.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("contacts", [Rule::required(), Rule::extensions(["csv", "txt"])]);Sourcepub const fn min_kilobytes(min: usize) -> Rule
pub const fn min_kilobytes(min: usize) -> Rule
Requires an uploaded file of at least this many kilobytes, of 1,024 bytes each. For a list, every file must pass.
Sourcepub const fn max_kilobytes(max: usize) -> Rule
pub const fn max_kilobytes(max: usize) -> Rule
Allows an uploaded file of at most this many kilobytes, of 1,024 bytes each. For a list, every file must pass.
Sourcepub fn required_if(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn required_if( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires a nonempty value when another field has a given value.
A string matches only the exact same string. A boolean or number also matches input that
the request decoder reads as that value, such as "1" for 1. The rule passes when the
other field is missing. The other _if and _unless rules treat a missing field as null.
use laravel::validation::{Rule, Rules};
use serde_json::json;
let rules = Rules::new()
.nullable("address")
.field("address", [Rule::required_if("delivery", "ship")]);
let input = serde_json::from_value(json!({ "delivery": "ship" }))?;
assert!(rules.validate(&input).await.is_err());Sourcepub fn required_unless(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn required_unless( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires a nonempty value unless another field has a given value. The values compare as for
Rule::required_if.
Sourcepub fn required_with(
fields: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn required_with( fields: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires a nonempty value when any of the named fields has a nonempty value.
Sourcepub fn required_with_all(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn required_with_all( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires a nonempty value when all of the named fields have nonempty values.
Sourcepub fn required_without(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn required_without( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires a nonempty value when any of the named fields is empty or missing.
Sourcepub fn required_without_all(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn required_without_all( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires a nonempty value when all of the named fields are empty or missing.
Sourcepub fn required_if_accepted(field: impl Into<String>) -> Rule
pub fn required_if_accepted(field: impl Into<String>) -> Rule
Requires a nonempty value when another field is accepted, as Rule::accepted checks.
Sourcepub fn required_if_declined(field: impl Into<String>) -> Rule
pub fn required_if_declined(field: impl Into<String>) -> Rule
Requires a nonempty value when another field is declined, as Rule::declined checks.
Sourcepub fn prohibited_if(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn prohibited_if( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Rejects a nonempty value when another field has a given value. The values compare as for
Rule::required_if.
Sourcepub fn prohibited_unless(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn prohibited_unless( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires an empty value unless another field has a given value. The values compare as for
Rule::required_if.
Sourcepub fn prohibited_if_accepted(field: impl Into<String>) -> Rule
pub fn prohibited_if_accepted(field: impl Into<String>) -> Rule
Requires an empty value when another field is accepted.
Sourcepub fn prohibited_if_declined(field: impl Into<String>) -> Rule
pub fn prohibited_if_declined(field: impl Into<String>) -> Rule
Requires an empty value when another field is declined.
Sourcepub fn prohibits(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn prohibits(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires the named fields to be empty when this field has a nonempty value.
Sourcepub fn accepted_if(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn accepted_if( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires an accepted value, as Rule::accepted checks, when another field has a given
value. The values compare as for Rule::required_if.
Sourcepub fn declined_if(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn declined_if( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires a declined value, as Rule::declined checks, when another field has a given
value. The values compare as for Rule::required_if.
Sourcepub fn present_if(field: impl Into<String>, value: impl Into<RuleValue>) -> Rule
pub fn present_if(field: impl Into<String>, value: impl Into<RuleValue>) -> Rule
Requires the field to be submitted when another field has a given value. The values compare
as for Rule::required_if.
Sourcepub fn present_unless(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn present_unless( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires the field to be submitted unless another field has a given value. The values
compare as for Rule::required_if.
Sourcepub fn present_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn present_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires the field to be submitted when any of the named fields is submitted.
Sourcepub fn present_with_all(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn present_with_all( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires the field to be submitted when all of the named fields are submitted.
Sourcepub fn missing_if(field: impl Into<String>, value: impl Into<RuleValue>) -> Rule
pub fn missing_if(field: impl Into<String>, value: impl Into<RuleValue>) -> Rule
Requires the field to be missing when another field has a given value. The values compare
as for Rule::required_if.
Sourcepub fn missing_unless(
field: impl Into<String>,
value: impl Into<RuleValue>,
) -> Rule
pub fn missing_unless( field: impl Into<String>, value: impl Into<RuleValue>, ) -> Rule
Requires the field to be missing unless another field has a given value. The values compare
as for Rule::required_if.
Sourcepub fn missing_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn missing_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires the field to be missing when any of the named fields is submitted.
Sourcepub fn missing_with_all(
values: impl IntoIterator<Item = impl Into<String>>,
) -> Rule
pub fn missing_with_all( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule
Requires the field to be missing when all of the named fields are submitted.
Sourcepub const fn min_items(min: usize) -> Rule
pub const fn min_items(min: usize) -> Rule
Requires at least this many entries in an array or object, or this many uploaded files. Other
values fail with the array message.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("tags", [Rule::min_items(1), Rule::max_items(10)]);Sourcepub const fn max_items(max: usize) -> Rule
pub const fn max_items(max: usize) -> Rule
Allows at most this many entries in an array or object, or this many uploaded files. Other
values fail with the array message.
Sourcepub const fn distinct() -> Rule
pub const fn distinct() -> Rule
Requires the values of a submitted array or object to differ from each other. The comparison
is case-sensitive and keeps JSON types, so 1, 1.0, and "1" are all different. Any other
value fails with the array message.
Sourcepub fn contains(values: impl IntoIterator<Item = impl Into<RuleValue>>) -> Rule
pub fn contains(values: impl IntoIterator<Item = impl Into<RuleValue>>) -> Rule
Requires a submitted array or object to contain every one of these values.
The comparison is case-sensitive and keeps JSON types, so 1, 1.0, and "1" are all
different. Objects compare without regard to key order. A value listed twice needs only one
match. An empty list accepts any array or object.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("roles", [Rule::contains(["editor", "reviewer"])]);
let numbers = Rules::new().field("values", [Rule::contains([1, 2])]);Sourcepub fn doesnt_contain(
values: impl IntoIterator<Item = impl Into<RuleValue>>,
) -> Rule
pub fn doesnt_contain( values: impl IntoIterator<Item = impl Into<RuleValue>>, ) -> Rule
Rejects a submitted array or object that contains any of these values.
The values compare as for Rule::contains. An empty list accepts any array or object. The
rule compares an object’s values, not its keys.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("roles", [Rule::doesnt_contain(["admin", "root"])]);Sourcepub const fn list() -> Rule
pub const fn list() -> Rule
Requires an array, or an object whose keys count up from zero in submitted order.
Every array and every empty object passes. An object’s numeric keys must be written as
plain decimal text, such as "2" rather than "02".
use laravel::validation::{Rule, Rules, Validate};
#[derive(serde::Deserialize, Validate)]
struct Post {
#[validate(list, each(required))]
tags: Vec<String>,
}
let rules = Rules::new().field("tags", [Rule::list()]).each_value("tags", [Rule::required()]);Sourcepub fn allowed_keys(keys: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn allowed_keys(keys: impl IntoIterator<Item = impl Into<String>>) -> Rule
Allows only these keys in a submitted object or array.
Each key is a literal name, so a dot or an asterisk in it doesn’t mean a path or a wildcard.
Name array indexes as plain decimal text, such as "0". An empty list accepts only an empty
array or object. Custom messages may use the :values and :unexpected placeholders.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("preferences", [Rule::allowed_keys(["theme", "locale"])]);Sourcepub fn required_keys(keys: impl IntoIterator<Item = impl Into<String>>) -> Rule
pub fn required_keys(keys: impl IntoIterator<Item = impl Into<String>>) -> Rule
Requires a submitted object or array to have each of these keys.
A key with a null or blank value still counts as present. Keys compare as for
Rule::allowed_keys. An empty list accepts any array or object. The rule doesn’t run when
the field is missing, so add Rule::required to require the field itself.
use laravel::validation::{Rule, Rules};
let rules = Rules::new().field("preferences", [Rule::required(), Rule::required_keys(["theme"])]);Sourcepub fn custom(rule: impl ValidationRule + 'static) -> Rule
pub fn custom(rule: impl ValidationRule + 'static) -> Rule
Wraps an application or package rule so a Rules builder can list it with
the built-in rules.
use laravel::validation::{Field, Rule, RuleError, Rules, ValidationRule};
struct Slug;
impl ValidationRule for Slug {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
match field.value.and_then(|value| value.as_str()) {
Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
_ => Err(field.reject("The :attribute field must be a slug.")),
}
}
}
let rules = Rules::new().field("slug", [Rule::bail(), Rule::string(), Rule::custom(Slug)]);Sourcepub fn custom_named(
name: &'static str,
rule: impl ValidationRule + 'static,
) -> Rule
pub fn custom_named( name: &'static str, rule: impl ValidationRule + 'static, ) -> Rule
Wraps a custom rule under a name, so Rules::message can override
its message.
The override applies only when the rule rejects input with Field::reject. In a derive
attribute, write phone = PhoneNumberRule to name a rule. When a named rule wraps another
named rule, the outer name takes precedence.
use laravel::validation::{Field, Rule, RuleError, Rules, ValidationRule};
struct Available;
impl ValidationRule for Available {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
Err(field.reject("The :attribute is unavailable."))
}
}
let rules = Rules::new()
.field("username", [Rule::custom_named("available", Available)])
.message("username", "available", "Choose another :attribute.");Trait Implementations§
Source§impl DatabaseRules for Rule
impl DatabaseRules for Rule
Source§fn unique<M, C>(column: Column<M, C>) -> Unique
fn unique<M, C>(column: Column<M, C>) -> Unique
column, such as an email address
that no other user has. The rule queries the model’s connection. Read moreSource§fn exists<M, C>(column: Column<M, C>) -> Exists
fn exists<M, C>(column: Column<M, C>) -> Exists
column, such as the ID of a
category that exists. The rule queries the model’s connection and decodes the value as the
column’s type, as for Rule::unique. Read moreSource§impl From<PasswordRule> for Rule
Converts password requirements into a rule for one field, in place of the application’s
defaults that Rule::password checks.
impl From<PasswordRule> for Rule
Converts password requirements into a rule for one field, in place of the application’s
defaults that Rule::password checks.
use laravel::validation::{PasswordRule, Rule, Rules};
let rules = Rules::new().field("password", [Rule::required(), Rule::from(PasswordRule::min(12).symbols())]);Source§fn from(rule: PasswordRule) -> Rule
fn from(rule: PasswordRule) -> Rule
Source§impl From<Regex> for Rule
Converts a Regex you built yourself, such as with RegexBuilder,
into a rule. Like Rule::regex, the rule passes when the pattern matches anywhere in the
text.
impl From<Regex> for Rule
Converts a Regex you built yourself, such as with RegexBuilder,
into a rule. Like Rule::regex, the rule passes when the pattern matches anywhere in the
text.
use laravel::validation::{Rule, regex::RegexBuilder};
let pattern = RegexBuilder::new(r"\A[a-z]+\z").size_limit(1 << 16).build()?;
let rule = Rule::from(pattern);Source§impl ValidationRule for Rule
impl ValidationRule for Rule
Auto Trait Implementations§
impl !RefUnwindSafe for Rule
impl !UnwindSafe for Rule
impl Forget for Rule
impl Freeze for Rulewhere
*const ArcInner<dyn ErasedRule> is !null: Freeze,
PhantomData<ArcInner<dyn ErasedRule>>: Freeze,
&'static str: Freeze,
*const u8 is !null: Freeze,
PhantomData<String>: Freeze,
PhantomData<u8>: Freeze,
PhantomData<Value>: Freeze,
PhantomData<usize>: Freeze,
PhantomData<Bucket<String, Value>>: Freeze,
*const Kind is !null: Freeze,
PhantomData<Kind>: Freeze,
*const ArcInner<RegexI> is !null: Freeze,
PhantomData<ArcInner<RegexI>>: Freeze,
*const Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>> is !null: Freeze,
PhantomData<Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>>>: Freeze,
*const ArcInner<str> is !null: Freeze,
PhantomData<ArcInner<str>>: Freeze,
*const ArcInner<dyn DatabaseRule> is !null: Freeze,
PhantomData<ArcInner<dyn DatabaseRule>>: Freeze,
PhantomData<InputValue>: Freeze,
impl Move for Rule
impl Send for Rule
impl Sync for Rule
impl Unpin for Rule
impl UnsafeUnpin for Rulewhere
*const ArcInner<dyn ErasedRule> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn ErasedRule>>: UnsafeUnpin,
&'static str: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<String>: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
PhantomData<Value>: UnsafeUnpin,
PhantomData<usize>: UnsafeUnpin,
PhantomData<Bucket<String, Value>>: UnsafeUnpin,
*const Kind is !null: UnsafeUnpin,
PhantomData<Kind>: UnsafeUnpin,
*const ArcInner<RegexI> is !null: UnsafeUnpin,
PhantomData<ArcInner<RegexI>>: UnsafeUnpin,
*const Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>> is !null: UnsafeUnpin,
PhantomData<Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>>>: UnsafeUnpin,
*const ArcInner<str> is !null: UnsafeUnpin,
PhantomData<ArcInner<str>>: UnsafeUnpin,
*const ArcInner<dyn DatabaseRule> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn DatabaseRule>>: UnsafeUnpin,
PhantomData<InputValue>: UnsafeUnpin,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<K> ForeignKey<K> for K
impl<K> ForeignKey<K> for K
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more