Skip to main content

Rule

Struct Rule 

Source
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) is Rule::decimal_between.
  • A bare url is Rule::url(["http", "https"]), and a bare uuid is Rule::uuid(None).
  • Rule::regex, Rule::not_regex, and Rule::date_format return a Result, because a pattern can be invalid. The attributes check their patterns at compile time.
  • With a table name, exists("categories", "id") is Rule::exists_in::<i64>("categories", "id"), which names the field’s type, and unique("posts", "slug") is Rule::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

Source

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.

Source

pub const fn string() -> Rule

Requires a string without converting numbers or booleans to text.

Source

pub const fn min_length(min: usize) -> Rule

Requires at least this many Unicode scalar values in a string.

Source

pub const fn max_length(max: usize) -> Rule

Allows at most this many Unicode scalar values in a string.

Source

pub fn one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule

Requires a scalar whose text representation is one of these choices.

Source

pub fn not_one_of(values: impl IntoIterator<Item = impl Into<String>>) -> Rule

Rejects scalars whose text representation is one of these choices.

Source

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.

Source

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.

Source

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.

Source

pub const fn alpha() -> Rule

Requires a string containing only Unicode letters and combining marks.

Source

pub const fn alpha_num() -> Rule

Requires a string or number made of Unicode letters, marks, or numbers.

Source

pub const fn alpha_dash() -> Rule

Requires a string or number made of Unicode letters, marks, numbers, dashes, or underscores.

Source

pub const fn ascii() -> Rule

Requires a string containing only ASCII characters, including control characters.

Source

pub const fn lowercase() -> Rule

Requires a string that Unicode lowercasing leaves unchanged.

Source

pub const fn uppercase() -> Rule

Requires a string that Unicode uppercasing leaves unchanged.

Source

pub fn starts_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule

Requires a string that starts with one of these prefixes.

Source

pub fn ends_with(values: impl IntoIterator<Item = impl Into<String>>) -> Rule

Requires a string that ends with one of these suffixes.

Source

pub fn doesnt_start_with( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule

Rejects a string that starts with one of these prefixes.

Source

pub fn doesnt_end_with( values: impl IntoIterator<Item = impl Into<String>>, ) -> Rule

Rejects a string that ends with one of these suffixes.

Source

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)]);
Source

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.

Source

pub const fn min_digits(min: usize) -> Rule

Requires at least this many ASCII digits.

Source

pub const fn max_digits(max: usize) -> Rule

Allows at most this many ASCII digits.

Source

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)]);
Source

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)]);
Source

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)]);
Source

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")]);
Source

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")]);
Source

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")]);
Source

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")]);
Source

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)]);
Source

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)]);
Source

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());
Source

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()]);
Source

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()]);
Source

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"])?]);
Source

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()]);
Source

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")]);
Source

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")]);
Source

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()]);
Source

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()]);
Source

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()]);
Source

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()]);
Source

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")]);
Source

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")]);
Source

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")]);
Source

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()]);
Source

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"])]);
Source

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)]);
Source

pub const fn ulid() -> Rule

Requires a ULID in canonical form, in either case.

Source

pub const fn ip() -> Rule

Requires an IPv4 or IPv6 address.

Source

pub const fn ipv4() -> Rule

Requires an IPv4 address.

Source

pub const fn ipv6() -> Rule

Requires an IPv6 address.

Source

pub const fn mac_address() -> Rule

Requires a MAC address whose groups are separated by colons, hyphens, or dots.

Source

pub const fn hex_color() -> Rule

Requires a # followed by 3, 4, 6, or 8 hexadecimal digits.

Source

pub const fn json() -> Rule

Requires a string that holds valid JSON, including a scalar such as null or 12.

Source

pub const fn base64() -> Rule

Requires a string in canonical padded Base64 encoding.

Source

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,
}
Source

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")?;
Source

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)]);
Source

pub const fn filled() -> Rule

Requires a nonempty value when the field is submitted. The rule passes when the field is missing.

Source

pub const fn present() -> Rule

Requires the field to be submitted. A submitted null or empty value passes.

Source

pub const fn missing() -> Rule

Requires the field to be missing. A submitted null fails.

Source

pub const fn prohibited() -> Rule

Requires the field to be missing or empty.

Source

pub const fn accepted() -> Rule

Requires "yes", "on", "1", 1, true, or "true".

Source

pub const fn declined() -> Rule

Requires "no", "off", "0", 0, false, or "false".

Source

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()]);
Source

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()]);
Source

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)]);
Source

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.

Source

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/*"])]);
Source

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"])]);
Source

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.

Source

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.

Source

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());
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn required_if_accepted(field: impl Into<String>) -> Rule

Requires a nonempty value when another field is accepted, as Rule::accepted checks.

Source

pub fn required_if_declined(field: impl Into<String>) -> Rule

Requires a nonempty value when another field is declined, as Rule::declined checks.

Source

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.

Source

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.

Source

pub fn prohibited_if_accepted(field: impl Into<String>) -> Rule

Requires an empty value when another field is accepted.

Source

pub fn prohibited_if_declined(field: impl Into<String>) -> Rule

Requires an empty value when another field is declined.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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)]);
Source

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.

Source

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.

Source

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])]);
Source

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"])]);
Source

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()]);
Source

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"])]);
Source

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"])]);
Source

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)]);
Source

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 Clone for Rule

Source§

fn clone(&self) -> Rule

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl DatabaseRules for Rule

Source§

fn unique<M, C>(column: Column<M, C>) -> Unique
where M: Model, C: DeserializeOwned + Into<Value<'static>>,

Requires a value that no row of the model’s table has in column, such as an email address that no other user has. The rule queries the model’s connection. Read more
Source§

fn exists<M, C>(column: Column<M, C>) -> Exists
where M: Model, C: DeserializeOwned + Into<Value<'static>>,

Requires a value that some row of the model’s table has in 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 more
Source§

fn unique_in<T>(table: impl Into<String>, column: impl Into<String>) -> Unique
where T: DeserializeOwned + Into<Value<'static>>,

Requires a value that no row of a table has in a column, like Rule::unique, for a table without a model. Read more
Source§

fn exists_in<T>(table: impl Into<String>, column: impl Into<String>) -> Exists
where T: DeserializeOwned + Into<Value<'static>>,

Requires a value that some row of a table has in a column, like Rule::exists, for a table without a model. Read more
Source§

impl Debug for Rule

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl From<Exists> for Rule

Source§

fn from(rule: Exists) -> Self

Converts to this type from the input type.
Source§

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

Converts to this type from the input type.
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.

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§

fn from(pattern: Regex) -> Rule

Converts to this type from the input type.
Source§

impl From<Unique> for Rule

Source§

fn from(rule: Unique) -> Self

Converts to this type from the input type.
Source§

impl ValidationRule for Rule

Source§

async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError>

Checks the submitted field. Read more
Source§

fn implicit(&self) -> bool

Returns whether the rule also runs on missing values, blank strings, and null on nullable fields. The default implementation returns false.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Rule

§

impl !UnwindSafe for Rule

§

impl Forget for Rule

§

impl Freeze for Rule
where *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
where Arc<dyn ErasedRule>: Send, &'static str: Send, RawVecInner: Send, RawTable<usize>: Send, BoxRaw<Kind>: Send, Arc<RegexI>: Send, BoxRaw<Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>>>: Send, Arc<str>: Send, Arc<dyn DatabaseRule>: Send, Arc<Stored>: Send,

§

impl Sync for Rule
where Arc<dyn ErasedRule>: Sync, RawVecInner: Sync, RawTable<usize>: Sync, BoxRaw<Kind>: Sync, Arc<RegexI>: Sync, BoxRaw<Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>>>: Sync, Arc<str>: Sync, Arc<dyn DatabaseRule>: Sync, Arc<Stored>: Sync,

§

impl Unpin for Rule
where Arc<dyn ErasedRule>: Unpin, &'static str: Unpin, *const u8 is !null: Unpin, Box<Kind>: Unpin, Arc<RegexI>: Unpin, Box<Pool<Cache, Box<dyn Fn() -> Cache + Sync + Send + UnwindSafe + RefUnwindSafe>>>: Unpin, Arc<str>: Unpin, Arc<dyn DatabaseRule>: Unpin, Arc<Stored>: Unpin,

§

impl UnsafeUnpin for Rule
where *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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> FillValue<Option<T>> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<Option<T>, Error>

Resolves the column’s value. Read more
Source§

impl<T> FillValue<T> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<T, Error>

Resolves the column’s value. Read more
Source§

impl<K> ForeignKey<K> for K

Source§

fn key(&self) -> Option<&K>

Returns the key, or None when the field holds no key.
Source§

fn __from_key(key: K) -> K

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T, N> NotifiedBy<T> for N
where T: Notification<N>,

Source§

fn __routes(&self) -> Vec<Route>

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, V> UpdateValue<T> for V
where V: FillValue<T>,

Source§

fn __update<M, U>(self, column: Column<M, T>, update: U) -> U
where M: Model, U: Updates<M>, T: IntoExpr + Clone + Send + Sync + 'static,

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more