Skip to main content

Validate

Struct Validate 

Source
pub struct Validate { /* private fields */ }
Expand description

验证器 — 对齐 PHP think\Validate

§用法

use sz_rust_infra_facade::validate::Validate;
use serde_json::json;

let mut v = Validate::new()
    .rule("name", "require")
    .rule("age", "require|integer");
let data = json!({"name": "Alice", "age": 30});
assert!(v.check(&data).is_ok());

Implementations§

Source§

impl Validate

Source

pub fn new() -> Validate

创建新的验证器

Source

pub fn rule(self, name: &str, rule: &str) -> Validate

添加字段验证规则

对齐 PHP rule($name, $rule = '')(第 286-298 行)

§参数
  • name:字段名(支持 field|title 格式指定字段描述)
  • rule:验证规则(字符串形式,如 "require|in:1,2,3"
Source

pub fn message(self, messages: IndexMap<String, String>) -> Validate

设置提示信息

对齐 PHP message(array $message)(第 341-346 行)

Source

pub fn field(self, fields: IndexMap<String, String>) -> Validate

设置字段描述

对齐 PHP rule() 方法中 $rule 为数组时合并到 $this->field

Source

pub fn scene(self, name: &str) -> Validate

设置验证场景

对齐 PHP scene(string $name)(第 354-360 行)

Source

pub fn register_scene(self, name: &str, fields: Vec<String>) -> Validate

注册场景字段列表

对齐 PHP $this->scene[$name] = $fields 属性赋值

Source

pub fn register_scene_callback( self, name: &str, callback: Arc<dyn Fn(&mut Validate) + Send + Sync>, ) -> Validate

注册场景回调 — 对齐 PHP protected function scene{Name}()

场景回调支持。回调签名 Fn(&mut Validate) + Send + Sync, 回调内部可调用 Validate::only_mutValidate::append_mutValidate::remove_mut 修改场景状态。

§PHP 对齐
protected function sceneLogin()
{
    return $this->only(['email']);
}

Rust 等价:

use std::sync::Arc;
v.register_scene_callback("login", Arc::new(|v| {
    v.only_mut(vec!["email".to_string()]);
}));
§优先级

对齐 PHP getScene(第 1663-1668 行):回调优先于数组形式。 如果同一场景名同时注册了数组和回调,回调会被调用,数组被忽略。

Source

pub fn has_scene(&self, name: &str) -> bool

判断是否存在某个验证场景

对齐 PHP hasScene(string $name)(第 368-371 行)

§PHP 行为

return isset($this->scene[$name]) || method_exists($this, 'scene' . $name);

Rust 实现:检查 scene 数组 scene_callbacks 映射

Source

pub fn batch(self, batch: bool) -> Validate

设置批量验证

对齐 PHP batch(bool $batch = true)(第 379-384 行)

Source

pub fn only(self, fields: Vec<String>) -> Validate

指定需要验证的字段列表

对齐 PHP only(array $fields)(第 405-410 行)

Source

pub fn remove(self, field: &str, rule: Option<Vec<String>>) -> Validate

移除某个字段的验证规则

对齐 PHP remove($field, $rule = null)(第 419-438 行)

§参数
  • field:字段名
  • rule:要移除的规则列表(None 表示移除所有规则)
Source

pub fn append(self, field: &str, rule: Vec<String>) -> Validate

追加某个字段的验证规则

对齐 PHP append($field, $rule = null)(第 447-462 行)

Source

pub fn only_mut(&mut self, fields: Vec<String>)

指定需要验证的字段列表(&mut self 版本)

对齐 PHP only(array $fields)&mut self 语义,供 scene 回调使用。 对齐 PHP sceneXxx 方法内部调用 $this->only([...])

Source

pub fn remove_mut(&mut self, field: &str, rule: Option<Vec<String>>)

移除某个字段的验证规则(&mut self 版本)

对齐 PHP remove($field, $rule = null)&mut self 语义,供 scene 回调使用。

Source

pub fn append_mut(&mut self, field: &str, rule: Vec<String>)

追加某个字段的验证规则(&mut self 版本)

对齐 PHP append($field, $rule = null)&mut self 语义,供 scene 回调使用。

Source

pub fn extend( &mut self, type_name: &str, callback: Arc<dyn Fn(&Value, &str, &Value) -> bool + Send + Sync>, ) -> &mut Validate

注册验证类型(自定义规则回调)

对齐 PHP extend(string $type, callable $callback, string $message = null)(第 308-317 行)

Source

pub fn regex(self, name: &str, pattern: &str) -> Validate

设置自定义正则

对齐 PHP $this->regex 属性

Source

pub fn set_lang(self, lang: Arc<dyn Lang>) -> Validate

设置多语言实例 — 对齐 PHP setLang(Lang $lang)

对齐 PHP Validate.php 第 252-255 行

§PHP 行为
public function setLang(Lang $lang)
{
    $this->lang = $lang;
}
§参数
  • lang:多语言实例(Arc<dyn Lang>
§用法
use std::sync::Arc;
use sz_rust_infra_facade::validate::Validate;
use sz_rust_infra_facade::validate::message::{Lang, SimpleLang};

let lang: Arc<dyn Lang> = Arc::new(
    SimpleLang::new().set("not conform to the rules", "不符合规则")
);
let v = Validate::new().set_lang(lang);
Source

pub fn check(&mut self, data: &Value) -> Result<(), ValidateError>

数据自动验证 — 对齐 PHP check(array $data, array $rules = [])

对齐 PHP Validate.php 第 471-540 行

§参数
  • data:待验证数据(JSON Object)
§返回
  • Ok(()):所有规则通过
  • Err(ValidateError):验证失败
Source

pub fn check_rule(&self, value: &Value, rules: &str) -> Result<(), String>

根据验证规则验证数据 — 对齐 PHP checkRule($value, $rules)

对齐 PHP Validate.php 第 549-581 行

§参数
  • value:字段值
  • rules:验证规则(字符串形式,如 "require|in:1,2,3"
§返回
  • Ok(()):所有规则通过
  • Err(String):验证失败,包含错误信息
Source

pub fn get_data_value(data: &Value, key: &str) -> Value

获取数据值 — 对齐 PHP getDataValue

对齐 PHP Validate.php 第 1536-1554 行

§PHP 行为(R5-3)
  • 数值型 key:返回 key 本身(PHP 怪异行为,复刻)
  • 包含 . 的 key:按多维数组访问
  • 其他 key:返回 data[key] 或 null
Source

pub fn get_validate_type( rule_type: &str, rule_args: &str, ) -> (String, String, String)

获取当前验证类型及规则 — 对齐 PHP getValidateType

对齐 PHP Validate.php 第 678-706 行

§PHP 行为(R5-4)
  • 别名映射(>gt>=egt 等)
  • 返回 (type, args, info)
    • type:用于分发的回调名(考虑别名)
    • args:规则参数
    • info:原始规则名(用于 remove/append 匹配)
Source

pub fn get_rule_msg( &self, field: &str, title: &str, type_name: &str, rule: &str, ) -> String

获取验证规则的错误提示信息 — 对齐 PHP getRuleMsg

对齐 PHP Validate.php 第 1565-1586 行

§PHP 查找优先级(R5-1)
  1. message[field.type]
  2. message[field]
  3. type_msg[type]
  4. 如果 type 以 require 开头,使用 type_msg['require']
  5. 默认 $title . $this->lang->get('not conform to the rules')
§Lang 翻译

所有分支的 msg 在占位符替换前先经过 Self::parse_error_msg_with_lang 进行 Lang 翻译(对齐 PHP parseErrorMsg 第 1598-1602 行)。 默认分支直接调用 lang->get('not conform to the rules')(对齐 PHP 第 1578 行)。

Source

pub fn parse_error_msg_with_lang( &self, msg: &str, rule: &str, title: &str, ) -> String

解析错误提示(含 Lang 翻译) — 对齐 PHP parseErrorMsg

对齐 PHP Validate.php 第 1596-1633 行

§PHP 行为
  1. Lang 翻译(第 1598-1602 行,R5-7):
    • {%var} 语法:lang->get(substr($msg, 2, -1))
    • lang->has($msg)lang->get($msg)
  2. 占位符替换(第 1613-1630 行,R5-2):
    • :attribute → title
    • :1 / :2 / :3 → rule 按逗号分割后的前 3 个元素
    • :rule → rule 原值(仅当 msg 包含 :rule 时)
§无 Lang 实例时的行为

Validate::langNone 时跳过翻译,直接执行占位符替换。 对齐 PHP 未注入 Lang 时的行为(PHP 中 $this->lang 必须存在,否则 parseErrorMsg 会致命错误;Rust 使用 Option 提供更安全的降级)。

Source

pub fn parse_error_msg(msg: &str, rule: &str, title: &str) -> String

解析错误提示 — 对齐 PHP parseErrorMsg 占位符替换部分

对齐 PHP Validate.php 第 1613-1630 行(不含 Lang 翻译)

§PHP 占位符替换(R5-2)
  1. :attribute → title
  2. :1 / :2 / :3 → rule 按逗号分割后的前 3 个元素
  3. :rule → rule 原值(仅当 msg 包含 :rule 时)
§说明

本方法为静态方法,不包含 Lang 翻译。如需 Lang 翻译,请使用 Self::parse_error_msg_with_lang 实例方法。

Source

pub fn get_error(&self) -> &ValidateError

获取错误信息 — 对齐 PHP getError()

Source

pub fn require(value: &Value, _rule: &str) -> bool

必须验证 — 对齐 PHP require

对齐 PHP Validate.php 第 814-817 行(实际由 is 处理 require)

§行为
  • nullfalse
  • 空字符串 ""false
  • 字符串 "0"true(PHP 特殊行为)
  • 其他非空值 → true
Source

pub fn must(value: &Value, _rule: &str) -> bool

必须验证(与 require 等价) — 对齐 PHP must

对齐 PHP Validate.php 第 814-817 行

Source

pub fn is(value: &Value, rule: &str, _data: &Value) -> bool

验证字段值是否为有效格式 — 对齐 PHP is

对齐 PHP Validate.php 第 827-888 行

§支持的类型
  • require:必须
  • accepted:接受(1/on/yes
  • date:有效日期
  • boolean/bool:布尔值
  • number:数字
  • integer:整数
  • float:浮点数
  • alpha:字母
  • alphaNum:字母数字
  • alphaDash:字母数字下划线短横线
  • chs:中文
  • chsAlpha:中文或字母
  • chsAlphaNum:中文或字母数字
  • chsDash:中文字母数字下划线短横线
  • mobile:手机号
  • email:邮箱
  • url:URL
  • ip:IP 地址
  • macAddr:MAC 地址
  • array:数组
Source

pub fn regex_validate( value: &Value, rule: &str, custom_regex: &IndexMap<String, String>, ) -> bool

正则验证 — 对齐 PHP regex

对齐 PHP Validate.php 第 1504-1518 行

Trait Implementations§

Source§

impl Default for Validate

Source§

fn default() -> Validate

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

Auto Trait Implementations§

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<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