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
impl Rules
Sourcepub fn field<M>(
self,
name: impl Into<String>,
rules: impl IntoRules<M>,
) -> Rules
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")).
Sourcepub fn label(self, name: impl Into<String>, label: impl Into<String>) -> Rules
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."]);Sourcepub fn message(
self,
name: impl Into<String>,
rule: impl Into<String>,
message: impl Into<String>,
) -> Rules
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.
Sourcepub fn item_label(
self,
name: impl Into<String>,
label: impl Into<String>,
) -> Rules
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.
Sourcepub fn item_message(
self,
name: impl Into<String>,
rule: impl Into<String>,
message: impl Into<String>,
) -> Rules
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."]);Sourcepub fn nullable(self, name: impl Into<String>) -> Rules
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.
Sourcepub fn sometimes(self, name: impl Into<String>) -> Rules
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.
Sourcepub fn alias(self, name: impl Into<String>, alias: impl Into<String>) -> Rules
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.
Sourcepub fn nested<T>(self, name: impl Into<String>) -> Ruleswhere
T: Validate,
pub fn nested<T>(self, name: impl Into<String>) -> Ruleswhere
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"));Sourcepub fn each<T>(self, name: impl Into<String>) -> Ruleswhere
T: Validate,
pub fn each<T>(self, name: impl Into<String>) -> Ruleswhere
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"));Sourcepub fn each_value<M>(
self,
name: impl Into<String>,
rules: impl IntoRules<M>,
) -> Rules
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"));Sourcepub fn keyed(self, name: impl Into<String>) -> Rules
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.
Sourcepub fn nullable_items(self, name: impl Into<String>) -> Rules
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.
Sourcepub async fn validate(
&self,
input: &Map<String, Value>,
) -> Result<(), ValidationError>
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§
Auto Trait Implementations§
impl !RefUnwindSafe for Rules
impl !UnwindSafe for Rules
impl Forget for Rules
impl Freeze for Ruleswhere
*const u8 is !null: Freeze,
PhantomData<usize>: Freeze,
PhantomData<Bucket<String, Definition>>: Freeze,
impl Move for Rules
impl Send for Rules
impl Sync for Rules
impl Unpin for Rules
impl UnsafeUnpin for Ruleswhere
*const u8 is !null: UnsafeUnpin,
PhantomData<usize>: UnsafeUnpin,
PhantomData<Bucket<String, Definition>>: 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
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