Skip to main content

Rules

Struct Rules 

Source
pub struct Rules(/* private fields */);
Expand description

A set of rules keyed by input field, with dotted paths for nested fields and list items.

use laravel::validation::{Rule, Rules};
use serde_json::json;

let rules = Rules::new().field("name", [Rule::required(), Rule::string(), Rule::max_length(100)]);
let input = serde_json::from_value(json!({ "name": "Taylor" }))?;

assert!(rules.validate(&input).await.is_ok());

Implementations§

Source§

impl Rules

Source

pub fn new() -> Rules

Returns an empty set of rules.

Source

pub fn field<M>( self, name: impl Into<String>, rules: impl IntoRules<M>, ) -> Rules

Adds rules for a field, after any rules the field already has. Pass an array or Vec of Rules, or a tuple to mix them with rule objects such as Unique, as in (Rule::required(), Rule::unique_in::<String>("users", "email")).

Source

pub fn label(self, name: impl Into<String>, label: impl Into<String>) -> Rules

Sets the field’s label, which messages show for :attribute. The errors stay keyed by the field’s path.

use laravel::validation::{Rule, Rules, ValidationError};
use serde_json::json;

let rules = Rules::new()
    .field("email", [Rule::required()])
    .label("email", "email address")
    .message("email", "required", "Please enter your :attribute.");

let input = serde_json::from_value(json!({}))?;

let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
    unreachable!();
};

assert_eq!(errors.errors()["email"], ["Please enter your email address."]);
Source

pub fn message( self, name: impl Into<String>, rule: impl Into<String>, message: impl Into<String>, ) -> Rules

Overrides the message of a built-in rule, a decoding error, or a named custom rule for one field. rule is the rule’s name, such as required or max_length. The available placeholders include :attribute, :min, :max, :other, and :values.

Source

pub fn item_label( self, name: impl Into<String>, label: impl Into<String>, ) -> Rules

Sets the label that messages show for each entry of a list field. The list itself keeps its own label.

Source

pub fn item_message( self, name: impl Into<String>, rule: impl Into<String>, message: impl Into<String>, ) -> Rules

Overrides the message of a built-in rule or a named custom rule for each entry of a list field. :index is the entry’s zero-based index, and :position is its one-based position. Both come from the first numeric segment of the input path.

use laravel::validation::{Rule, Rules, ValidationError};
use serde_json::json;

let rules = Rules::new()
    .each_value("tags", [Rule::required()])
    .item_label("tags", "tag")
    .item_message("tags", "required", "Tag #:position cannot be blank.");

let input = serde_json::from_value(json!({ "tags": [""] }))?;

let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
    unreachable!();
};

assert_eq!(errors.errors()["tags.0"], ["Tag #1 cannot be blank."]);
Source

pub fn nullable(self, name: impl Into<String>) -> Rules

Allows null for a field. When the field is null, its non-implicit rules don’t run.

Source

pub fn sometimes(self, name: impl Into<String>) -> Rules

Checks a field only when the input has it. When the field is missing, none of its rules run, including required. The derive calls this for a Sometimes field.

Source

pub fn alias(self, name: impl Into<String>, alias: impl Into<String>) -> Rules

Accepts another input name for a field, like serde’s alias. When the input has both names, the primary name’s value is used.

Source

pub fn nested<T>(self, name: impl Into<String>) -> Rules
where T: Validate,

Validates a submitted object with the rules of its type, T. The rules are built when validation first needs them. This replaces the field’s each or each_value rules.

The nested rules don’t check whether the object is present. Decoding or a required rule on the field reports a missing object. When a nullable object is null, its fields’ rules don’t run.

use laravel::validation::{Rules, Validate, ValidationError};
use serde_json::json;

#[derive(Validate)]
struct Address {
    #[validate(required)]
    city: String,
}

let rules = Rules::new().nested::<Address>("address");
let input = serde_json::from_value(json!({ "address": {} }))?;

let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
    unreachable!();
};

assert!(errors.errors().contains_key("address.city"));
Source

pub fn each<T>(self, name: impl Into<String>) -> Rules
where T: Validate,

Validates every object in a list with the rules of the item type, T. This replaces the field’s nested or each_value rules.

The item rules are built when validation first needs them, so an input type may contain a list of itself.

use laravel::validation::{Rules, Validate, ValidationError};
use serde_json::json;

#[derive(Validate)]
struct LineItem {
    #[validate(required, max_length = 20)]
    sku: String,
}

let rules = Rules::new().each::<LineItem>("items");
let input = serde_json::from_value(json!({ "items": [{ "sku": "" }] }))?;

let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
    unreachable!();
};

assert!(errors.errors().contains_key("items.0.sku"));
Source

pub fn each_value<M>( self, name: impl Into<String>, rules: impl IntoRules<M>, ) -> Rules

Applies rules to every value in a list, in declaration order. This replaces the field’s nested or each rules.

use laravel::validation::{Rule, Rules, ValidationError};
use serde_json::json;

let rules = Rules::new().each_value("tags", [Rule::required(), Rule::string(), Rule::max_length(20)]);
let input = serde_json::from_value(json!({ "tags": ["rust", ""] }))?;

let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
    unreachable!();
};

assert!(errors.errors().contains_key("tags.1"));
Source

pub fn keyed(self, name: impl Into<String>) -> Rules

Treats the field as a map, so its each and each_value rules check the value under every key, such as labels.home, not only list indexes.

Source

pub fn nullable_items(self, name: impl Into<String>) -> Rules

Allows null entries in a list field. For a null entry, the entry’s non-implicit rules don’t run.

Source

pub async fn validate( &self, input: &Map<String, Value>, ) -> Result<(), ValidationError>

Validates input without a request, collecting the errors of every field and list entry.

Non-implicit rules don’t run on missing fields or blank strings. They run on a submitted null unless the field is nullable. When a built-in presence rule such as required fails, the field’s remaining rules don’t run. With Rule::bail, any failed rule stops the field’s remaining rules, including the rules of its children.

§Errors

Returns ValidationError::Invalid when fields fail. Returns ValidationError::Failed when a custom rule’s check can’t run, which stops validation. It also returns Failed when a field has list entry settings, such as item_label or nullable_items, without each or each_value.

Without a request, the errors don’t carry old input for a form redirect, as the errors from Request::validate do. Rules that read the request, such as current_password, return a ValidationError::Failed with a 500.

Trait Implementations§

Source§

impl Debug for Rules

Source§

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

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

impl Default for Rules

Source§

fn default() -> Rules

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Rules

§

impl !UnwindSafe for Rules

§

impl Forget for Rules

§

impl Freeze for Rules
where *const u8 is !null: Freeze, PhantomData<usize>: Freeze, PhantomData<Bucket<String, Definition>>: Freeze,

§

impl Move for Rules

§

impl Send for Rules
where RawTable<usize>: Send, RawVecInner: Send, Arc<dyn ErasedRule>: Send, &'static str: 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 Rules
where RawTable<usize>: Sync, RawVecInner: Sync, Arc<dyn ErasedRule>: 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 Rules
where *const u8 is !null: Unpin, Arc<dyn ErasedRule>: Unpin, &'static str: 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 Rules
where *const u8 is !null: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, PhantomData<Bucket<String, Definition>>: 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> 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> 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, 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