pub struct Validator { /* private fields */ }Expand description
Checks input against a rule set.
use rainier_validation::{Rule, Validator};
use serde_json::json;
let validator = Validator::new()
.rules("email", vec![Rule::Required, Rule::Email])
.rules("age", vec![Rule::Integer, Rule::Min(18.0)]);
let errors = validator.validate(&json!({ "email": "not-an-email" })).unwrap_err();
assert_eq!(errors.first("email"), Some("The email field must be a valid email address."));
assert!(!errors.has("age"), "an absent optional field does not fail");Implementations§
Source§impl Validator
impl Validator
Sourcepub fn from_rules(rules: RuleSet) -> Self
pub fn from_rules(rules: RuleSet) -> Self
Build from a RuleSet.
Sourcepub fn rules(self, field: impl Into<String>, rules: Vec<Rule>) -> Self
pub fn rules(self, field: impl Into<String>, rules: Vec<Rule>) -> Self
Add rules for field.
field may be a dotted path (address.city) or contain * to reach
into an array (items.*.quantity).
Sourcepub fn custom_message(
self,
key: impl Into<String>,
message: impl Into<String>,
) -> Self
pub fn custom_message( self, key: impl Into<String>, message: impl Into<String>, ) -> Self
Override the message for one field.rule pair —
custom_message("email.required", "We need your email.").
Sourcepub fn custom_messages(
self,
messages: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self
pub fn custom_messages( self, messages: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>, ) -> Self
Add several custom messages.
Sourcepub fn validate(&self, input: &Value) -> Result<(), ValidationErrors>
pub fn validate(&self, input: &Value) -> Result<(), ValidationErrors>
Validate input, returning the failures.
Sourcepub fn validated(&self, input: &Value) -> Result<Value, ValidationErrors>
pub fn validated(&self, input: &Value) -> Result<Value, ValidationErrors>
Validate and hand back the input, for chaining.
Sourcepub fn validated_only(&self, input: &Value) -> Result<Value, ValidationErrors>
pub fn validated_only(&self, input: &Value) -> Result<Value, ValidationErrors>
Validate and keep only the fields that had rules.
This is a security feature, not a convenience: it is what stops a
client from smuggling an is_admin field into a mass assignment. Only
keys you wrote a rule for survive.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Validator
impl !UnwindSafe for Validator
impl Freeze for Validator
impl Send for Validator
impl Sync for Validator
impl Unpin for Validator
impl UnsafeUnpin for Validator
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
Mutably borrows from an owned value. Read more