開發程式的時候,常會需要讓程式能與使用者或其它程式互動,透過文字介面、圖形介面或是通訊協定標準,從外部取得資料來進行更進一步的處理。尤其是當使用者在使用我們的程式時,由於我們沒有辦法限制他們輸入的資料一定要符合程式設計的格式,程式很可能就會因錯誤的輸入而造成錯誤的輸出,甚至對整個系統的安全性造成威脅。所以通常我們在處理外部進來的資料時,會先檢查它們的格式後再進行處理。
Validators
「Validators」是筆者開發的套件,可以將使用者輸入的資料進行驗證並順便模型化(反序列化)。利用程序式巨集,在定義結構體的同時決定這個結構體要套用哪個驗證器(validator),以及設定相關的參數。
Crates.io
Cargo.toml
使用方法
特色
在預設下,這個crate所支援的每個驗證器都會被啟用。我們可以藉由關閉預設特色來禁用它們,並明確地啟用驗證器的特色來啟用該驗證器。
例如:
[dependencies.validators]
version = "*"
features = ["base64", "url", "uuid"]
default-features = false
某些驗證器並不需要標準函式庫的支援,但如果您有需要的話,還是可以明確地啟用std
特色來融入標準函式庫的功能。
這個crate也可以支援Serde和Rocket框架,只需分別啟用serde
和rocket
特色。
驗證器
use validators::prelude::*;
/*
#[derive(Validator)]
#[validator(validator_name)]
DEFINE_YOUR_STRUCT_HERE
*/
當我們替我們的結構體加上#[validator(validator_name)]
屬性後,一個或多個來自於validators::traits
模組中的特性就會被自動實作。這些特性在被實作後可以被用來做資料的驗證或是反序列化。
作為驗證器的結構體,必須要根據其是哪種驗證器以及驗證器的參數來定義它的組成欄位。例如,一個base32
的驗證器,結構體會長成這樣:struct(String)
;而一個base32_decoded
的驗證器,結構體會長成這樣:struct(Vec<u8>)
。
#[validator(validator_name)]
屬性不可以被用在結構體或是列舉中的欄位上。這個套件之所以會選擇使用程序式巨集來定義驗證器(結構體),而不是對每種驗證器的組態設定提供內建的結構體的原因是要讓可組態設定的驗證項目在程式執行階段不會有任何的開支(overhead),而且也可以提高編譯速度。
base32
use validators::prelude::*;
#[derive(Validator)]
#[validator(base32(padding(Must)))]
pub struct Base32WithPadding(String);
assert!(Base32WithPadding::parse_string("GEZDGNBVGY3TQOI=").is_ok());
assert!(Base32WithPadding::parse_string("GEZDGNBVGY3TQOI").is_err());
assert_eq!("GEZDGNBVGY3TQOI=", Base32WithPadding::parse_string("GEZDGNBVGY3TQOI=").unwrap().0);
- 特性:
ValidateString
、ValidateBytes
- 預設
padding = Allow
base32_decoded
use validators::prelude::*;
#[derive(Validator)]
#[validator(base32_decoded(padding(Must)))]
pub struct Base32WithPaddingDecoded(Vec<u8>);
assert!(Base32WithPaddingDecoded::parse_string("GEZDGNBVGY3TQOI=").is_ok());
assert!(Base32WithPaddingDecoded::parse_string("GEZDGNBVGY3TQOI").is_err());
assert_eq!(b"123456789", Base32WithPaddingDecoded::parse_string("GEZDGNBVGY3TQOI=").unwrap().0.as_slice());
- 特性:
ValidateString
、ValidateBytes
、CollectionLength
- 預設參數:
padding = Allow
base64
use validators::prelude::*;
#[derive(Validator)]
#[validator(base64(padding(Must)))]
pub struct Base64WithPadding(String);
assert!(Base64WithPadding::parse_string("MTIzNDU2Nzg5MA==").is_ok());
assert!(Base64WithPadding::parse_string("MTIzNDU2Nzg5MA").is_err());
assert_eq!("MTIzNDU2Nzg5MA==", Base64WithPadding::parse_string("MTIzNDU2Nzg5MA==").unwrap().0);
- 特性:
ValidateString
、ValidateBytes
- 預設
padding = Allow
base64_decoded
use validators::prelude::*;
#[derive(Validator)]
#[validator(base64_decoded(padding(Must)))]
pub struct Base64WithPaddingDecoded(Vec<u8>);
assert!(Base64WithPaddingDecoded::parse_string("MTIzNDU2Nzg5MA==").is_ok());
assert!(Base64WithPaddingDecoded::parse_string("MTIzNDU2Nzg5MA").is_err());
assert_eq!(b"1234567890", Base64WithPaddingDecoded::parse_string("MTIzNDU2Nzg5MA==").unwrap().0.as_slice());
- 特性:
ValidateString
、ValidateBytes
、CollectionLength
- 預設參數:
padding = Allow
base64_url
use validators::prelude::*;
#[derive(Validator)]
#[validator(base64_url(padding(Disallow)))]
pub struct Base64UrlWithoutPadding(String);
assert!(Base64UrlWithoutPadding::parse_string("5LmN5pqW6YKE5a-S5pmC5YCZ").is_ok());
assert!(Base64UrlWithoutPadding::parse_string("5LmN5pqW6YKE5a+S5pmC5YCZ").is_err());
assert_eq!("5LmN5pqW6YKE5a-S5pmC5YCZ", Base64UrlWithoutPadding::parse_string("5LmN5pqW6YKE5a-S5pmC5YCZ").unwrap().0);
- 特性:
ValidateString
、ValidateBytes
- 預設
padding = Allow
base64_url_decoded
use validators::prelude::*;
#[derive(Validator)]
#[validator(base64_url_decoded(padding(Disallow)))]
pub struct Base64UrlWithoutPaddingDecoded(Vec<u8>);
assert!(Base64UrlWithoutPaddingDecoded::parse_string("5LmN5pqW6YKE5a-S5pmC5YCZ").is_ok());
assert!(Base64UrlWithoutPaddingDecoded::parse_string("5LmN5pqW6YKE5a+S5pmC5YCZ").is_err());
assert_eq!("乍暖還寒時候".as_bytes(), Base64UrlWithoutPaddingDecoded::parse_string("5LmN5pqW6YKE5a-S5pmC5YCZ").unwrap().0.as_slice());
- 特性:
ValidateString
、ValidateBytes
、CollectionLength
- 預設參數:
padding = Allow
bit
use validators::prelude::*;
use validators::byte_unit::Bit;
#[derive(Validator)]
#[validator(bit(range(min = 1)))]
pub struct AtLeastOneBit(Bit);
assert!(AtLeastOneBit::parse_string("1kb").is_ok());
assert!(AtLeastOneBit::parse_string("0b").is_err());
assert_eq!(1000u64, AtLeastOneBit::parse_string("1kb").unwrap().0);
- 特性:
ValidateString
、ValidateBytes
、CollectionLength
- 預設參數:range無限制
boolean
use validators::prelude::*;
#[derive(Validator)]
#[validator(boolean)]
pub struct Boolean(bool);
assert_eq!(true, Boolean::parse_str("true").unwrap().0);
assert_eq!(false, Boolean::parse_str("f").unwrap().0);
assert_eq!(true, Boolean::parse_str("y").unwrap().0);
assert_eq!(false, Boolean::parse_str("no").unwrap().0);
assert_eq!(true, Boolean::parse_str("on").unwrap().0);
assert_eq!(false, Boolean::parse_str("off").unwrap().0);
assert_eq!(true, Boolean::parse_str("1").unwrap().0);
assert_eq!(true, Boolean::parse_char('t').unwrap().0);
assert_eq!(false, Boolean::parse_char('0').unwrap().0);
assert_eq!(true, Boolean::parse_isize(1).unwrap().0);
- 特性:
ValidateString
、ValidateChar
、ValidateSignedInteger
、ValidateUnsignedInteger
、ValidateBoolean
byte
use validators::prelude::*;
use validators::byte_unit::Byte;
#[derive(Validator)]
#[validator(byte(range(min = 1), ignore_case = false))]
pub struct AtLeastOneByte(Byte);
assert!(AtLeastOneByte::parse_string("1KB").is_ok());
assert!(AtLeastOneByte::parse_string("0B").is_err());
assert_eq!(1000u64, AtLeastOneByte::parse_string("1KB").unwrap().0);
- 特性:
ValidateString
、ValidateUnsignedInteger
- 預設參數:range無限制,
ignore_case = true
domain
use validators::prelude::*;
#[derive(Validator)]
#[validator(domain(ipv4(Allow), local(Allow), port(Disallow), at_least_two_labels(Allow)))]
pub struct DomainWithoutPort(pub String);
assert!(DomainWithoutPort::parse_string("example.com").is_ok());
assert!(DomainWithoutPort::parse_string("example.com.").is_ok());
assert_eq!("xn--fiq228c.com", DomainWithoutPort::parse_string("中文.com").unwrap().0);
#[derive(Validator)]
#[validator(domain(ipv4(Allow), local(Allow), port(Allow), at_least_two_labels(Allow)))]
pub struct DomainAllowPort {
pub domain: String,
port: Option<u16>,
}
assert_eq!(Some(8080), DomainAllowPort::parse_string("example.com:8080").unwrap().port);
- 特性:
ValidateString
、QualifyDomain
、QualifyDomain
- 預設參數:
ipv4 = Allow, local = Allow, port = Allow, at_least_two_labels = Allow
use validators::prelude::*;
use validators::models::Host;
#[derive(Validator)]
#[validator(email(comment(Allow), ip(Allow), local(Allow), at_least_two_labels(Allow), non_ascii(Allow)))]
pub struct EmailAllowComment {
pub local_part: String,
pub need_quoted: bool,
pub domain_part: Host,
pub comment_before_local_part: Option<String>,
pub comment_after_local_part: Option<String>,
pub comment_before_domain_part: Option<String>,
pub comment_after_domain_part: Option<String>,
}
assert!(EmailAllowComment::parse_string("(john)joke@example.com").is_ok());
#[derive(Validator)]
#[validator(email(comment(Disallow), ip(Allow), local(Allow), at_least_two_labels(Allow), non_ascii(Allow)))]
pub struct EmailWithoutComment {
pub local_part: String,
pub need_quoted: bool,
pub domain_part: Host,
}
assert!(EmailWithoutComment::parse_string("(john)joke@example.com").is_err());
- 特性:
ValidateString
、ToEmailString
- 預設參數:
comment = Allow, ip = Allow, local = Allow, at_least_two_labels = Allow, non_ascii = Allow
host
use validators::prelude::*;
use validators::models::Host;
#[derive(Validator)]
#[validator(host(local(Allow), port(Allow), at_least_two_labels(Must)))]
pub struct HostMustAtLeastTwoLabelsAllowPort {
pub host: Host,
pub port: Option<u16>,
pub is_local: bool,
}
assert!(HostMustAtLeastTwoLabelsAllowPort::parse_string("example.com:8000").is_ok());
assert!(HostMustAtLeastTwoLabelsAllowPort::parse_string("example.com.").is_err());
assert!(HostMustAtLeastTwoLabelsAllowPort::parse_string("example").is_err());
- 特性:
ValidateString
、ToUriAuthorityString
- 預設參數:
local = Allow, port = Allow, at_least_two_labels = Allow
http_url
use validators::prelude::*;
use validators::url::Url;
#[derive(Validator)]
#[validator(http_url(local(Allow)))]
pub struct HttpURL {
url: Url,
is_https: bool,
}
assert!(HttpURL::parse_string("https://example.org/").is_ok());
assert!(HttpURL::parse_string("http://example.org/").is_ok());
assert!(HttpURL::parse_string("ftp://example.org/").is_err());
- 特性:
ValidateString
- 預設參數:
local = Allow
http_ftp_url
use validators::prelude::*;
use validators::models::Protocol;
use validators::url::Url;
#[derive(Validator)]
#[validator(http_ftp_url(local(Allow)))]
pub struct HttpFtpURL {
url: Url,
protocol: Protocol,
}
assert!(HttpFtpURL::parse_string("https://example.org/").is_ok());
assert!(HttpFtpURL::parse_string("http://example.org/").is_ok());
assert!(HttpFtpURL::parse_string("ftp://example.org/").is_ok());
- 特性:
ValidateString
- 預設參數:
local = Allow
ip
use std::net::IpAddr;
use validators::prelude::*;
#[derive(Validator)]
#[validator(ip(local(Allow), port(Allow)))]
pub struct IpAllowPort {
pub ip: IpAddr,
pub port: Option<u16>,
}
assert!(IpAllowPort::parse_string("127.0.0.1").is_ok());
assert!(IpAllowPort::parse_string("[::ffff:c000:0280]:8000").is_ok());
- 特性:
ValidateString
、ToUriAuthorityString
- 預設參數:
local = Allow, port = Allow
ipv4
use std::net::Ipv4Addr;
use validators::prelude::*;
#[derive(Validator)]
#[validator(ipv4(local(Allow), port(Allow)))]
pub struct Ipv4AllowPort {
pub ipv4: Ipv4Addr,
pub port: Option<u16>,
}
assert!(Ipv4AllowPort::parse_string("127.0.0.1").is_ok());
- 特性:
ValidateString
、ToUriAuthorityString
- 預設參數:
local = Allow, port = Allow
ipv6
use std::net::Ipv6Addr;
use validators::prelude::*;
#[derive(Validator)]
#[validator(ipv6(local(Allow), port(Allow)))]
pub struct Ipv6AllowPort {
pub ipv6: Ipv6Addr,
pub port: Option<u16>,
}
assert!(Ipv6AllowPort::parse_string("::ffff:c000:0280").is_ok());
assert!(Ipv6AllowPort::parse_string("[::ffff:c000:0280]").is_ok());
- 特性:
ValidateString
、ToUriAuthorityString
- 預設參數:
local = Allow, port = Allow
json
use validators::prelude::*;
#[derive(Validator)]
#[validator(json)]
pub struct JSONString(pub String);
#[derive(Validator)]
#[validator(json)]
pub struct JSONNumber(pub f64);
#[derive(Validator)]
#[validator(json)]
pub struct JSONBoolean(pub bool);
assert!(JSONString::parse_string("123").is_err());
assert!(JSONString::parse_string("\"123\"").is_ok());
assert!(JSONNumber::parse_u64(123).is_ok());
assert!(JSONBoolean::parse_bool(false).is_ok());
- 特性:
ValidateString
、ValidateSignedInteger
、ValidateUnsignedInteger
、ValidateNumber
、ValidateBoolean
、ValidateJsonValue
length
use validators::prelude::*;
#[derive(Validator)]
#[validator(length(min = 1, max = 3))]
pub struct NonEmptyNotTooLongVec(pub Vec<u8>);
assert!(NonEmptyNotTooLongVec::parse_collection(vec![]).is_err());
assert!(NonEmptyNotTooLongVec::parse_collection(vec![0]).is_ok());
assert!(NonEmptyNotTooLongVec::parse_collection(vec![0, 1, 2, 3]).is_err());
- 特性:
ValidateLength
、CollectionLength
- 預設參數:length無限制
line
use validators::prelude::*;
#[derive(Validator)]
#[validator(line(char_length(trimmed_min = 1, min = 1, max = 1000)))] // `byte_length` can also be used
pub struct LineNotAllowEmpty(pub String);
assert!(LineNotAllowEmpty::parse_string("123").is_ok());
assert!(LineNotAllowEmpty::parse_string("123\0").is_err());
assert!(LineNotAllowEmpty::parse_string("123\n456").is_err());
assert!(LineNotAllowEmpty::parse_string(" ").is_err());
- 特性:
ValidateString
- 預設參數:length無限制
mac_address
use validators::prelude::*;
#[derive(Validator)]
#[validator(mac_address(case(Upper), separator(Allow(b':'))))]
pub struct MacAddress(pub u64);
assert!(MacAddress::parse_string("080027B246C3").is_ok());
assert!(MacAddress::parse_string("08:00:27:B2:46:C3").is_ok());
- 特性:
ValidateString
、ToMacAddressString
- 預設參數:
case = Any, separator(Allow(b':')
number
use validators::prelude::*;
#[derive(Validator)]
#[validator(number(nan(Disallow), range(Unlimited)))]
pub struct Double(pub f64);
assert!(Double::parse_string("123.456").is_ok());
assert!(Double::parse_string("NaN").is_err());
assert!(Double::parse_f32(123.4).is_ok());
#[derive(Validator)]
#[validator(number(nan(Allow), range(Inside(min = 0, max = 1.0))))]
pub struct SinglePercentage(pub f32);
assert!(SinglePercentage::parse_string("0").is_ok());
assert!(SinglePercentage::parse_string("1").is_ok());
assert!(SinglePercentage::parse_string("1.1").is_err());
assert!(SinglePercentage::parse_string("NaN").is_ok());
- 特性:
ValidateString
、ValidateNumber
- 預設參數:
nan = Allow, range(Unlimited)
phone
use std::collections::HashMap;
use validators::prelude::*;
use validators_prelude::phonenumber::PhoneNumber;
#[derive(Validator)]
#[validator(phone)]
pub struct InternationalPhone(pub phonenumber::PhoneNumber);
#[derive(Validator)]
#[validator(phone(countries(TW)))]
pub struct TWPhone(pub phonenumber::PhoneNumber);
#[derive(Validator)]
#[validator(phone(countries(TW, US)))]
pub struct TWorUSPhone(
pub HashMap<phonenumber::country::Id, phonenumber::PhoneNumber>,
);
assert!(InternationalPhone::parse_string("+886912345678").is_ok());
assert!(InternationalPhone::parse_string("0912345678").is_err());
assert!(InternationalPhone::parse_string("+14155552671").is_ok());
assert!(TWPhone::parse_string("+886912345678").is_ok());
assert!(TWPhone::parse_string("0912345678").is_ok());
assert!(TWPhone::parse_string("+14155552671").is_err());
assert!(TWorUSPhone::parse_string("+886912345678").is_ok());
assert!(TWorUSPhone::parse_string("0912345678").is_ok());
assert!(TWorUSPhone::parse_string("+14155552671").is_ok());
- 特性:
ValidateString
- 預設參數:countries無限制
regex
use validators::prelude::*;
use validators_prelude::regex::Regex;
use once_cell::sync::Lazy;
static RE_NON_ZERO_NUMBERS: Lazy<Regex> = Lazy::new(|| {
Regex::new("^[1-9]+$").unwrap()
});
static RE_POKER: Lazy<Regex> = Lazy::new(|| {
Regex::new("^([AJQK1-9]|10)$").unwrap()
});
#[derive(Validator)]
#[validator(regex(regex("^[0-9a-fA-F]+$")))]
pub struct Hex(pub String); // this doesn't cache the `Regex` instance
#[derive(Validator)]
#[validator(regex(regex(RE_NON_ZERO_NUMBERS)))]
pub struct NonZeroNumbers(pub String);
#[derive(Validator)]
#[validator(regex(regex(RE_POKER)))]
pub struct Poker(pub String);
assert!(Hex::parse_string("1Ab").is_ok());
assert!(Hex::parse_string("1AG").is_err());
assert!(NonZeroNumbers::parse_string("12345").is_ok());
assert!(NonZeroNumbers::parse_string("012345").is_err());
assert!(Poker::parse_string("1").is_ok());
assert!(Poker::parse_string("10").is_ok());
assert!(Poker::parse_string("J").is_ok());
assert!(Poker::parse_string("0").is_err());
- 特性:
ValidateString
regex
參數必須設定
semver
use validators::prelude::*;
use validators_prelude::semver::Version;
#[derive(Validator)]
#[validator(semver)]
pub struct SemVer(Version);
assert!(SemVer::parse_string("0.0.0").is_ok());
assert!(SemVer::parse_string("0.0.0-beta.1").is_ok());
- 特性:
ValidateString
semver_req
use validators::prelude::*;
use validators_prelude::semver::VersionReq;
#[derive(Validator)]
#[validator(semver_req)]
pub struct SemVerReq(VersionReq);
assert!(SemVerReq::parse_string("0.0.0").is_ok());
assert!(SemVerReq::parse_string(">= 0.4").is_ok());
- 特性:
ValidateString
signed_integer
use validators::prelude::*;
#[derive(Validator)]
#[validator(signed_integer(range(Inside(min = -1, max = 100))))]
pub struct Score(i8);
assert!(Score::parse_string("0").is_ok());
assert!(Score::parse_string("-2").is_err());
assert!(Score::parse_i8(4).is_ok());
#[derive(Validator)]
#[validator(signed_integer(range(Outside(min = 0, max = 0))))]
pub struct NonZeroShort(i16);
assert!(NonZeroShort::parse_i8(4).is_ok());
assert!(NonZeroShort::parse_i8(-4).is_ok());
assert!(NonZeroShort::parse_i8(0).is_err());
- 特性:
ValidateString
、ValidateSignedInteger
- 預設參數:
range(Unlimited)
text
use validators::prelude::*;
#[derive(Validator)]
#[validator(text(char_length(trimmed_min = 1, min = 1, max = 1000)))] // `byte_length` can also be used
pub struct TextNotAllowEmpty(pub String);
assert!(TextNotAllowEmpty::parse_string("123").is_ok());
assert!(TextNotAllowEmpty::parse_string("123\0").is_err());
assert!(TextNotAllowEmpty::parse_string("123\n456").is_ok());
assert!(TextNotAllowEmpty::parse_string(" ").is_err());
- 特性:
ValidateString
- 預設參數:length無限制
unsigned_integer
use validators::prelude::*;
#[derive(Validator)]
#[validator(unsigned_integer(range(Inside(min = 1, max = 100))))]
pub struct Count(u8);
assert!(Count::parse_string("5").is_ok());
assert!(Count::parse_string("0").is_err());
assert!(Count::parse_u8(4).is_ok());
- 特性:
ValidateString
、ValidateUnsignedInteger
- 預設參數:
range(Unlimited)
url
use validators::prelude::*;
use validators_prelude::url::Url;
#[derive(Validator)]
#[validator(url)]
pub struct URL(pub Url);
assert!(URL::parse_string("https://example.org/").is_ok());
assert!(URL::parse_string("https:example.org").is_ok());
assert!(URL::parse_string("example:").is_ok());
- 特性:
ValidateString
uuid
use validators::prelude::*;
#[derive(Validator)]
#[validator(uuid(case(Upper), separator(Allow(b'-'))))]
pub struct UUID(pub u128);
assert!(UUID::parse_string("A866664AF9D34DDE89CB182015FA4F41").is_ok());
assert!(UUID::parse_string("A866664A-F9D3-4DDE-89CB-182015FA4F41").is_ok());
- 特性:
ValidateString
、ToUuidString
- 預設參數:
case = Any, separator(Allow(b'-')
validators::Result
當我們將我們的驗證器型別併入其它型別中時,我們也許會想要取得驗證器提供的錯誤型別的實體。
舉例來說,當要把number
驗證器的型別用於Rocket框架的#[derive(FromForm)]
屬性的型別中時,程式碼如下:
use rocket::{FromForm, get};
use validators::prelude::*;
#[derive(Debug, Validator)]
#[validator(number(range(Outside(max = 0))))]
pub struct NonZeroNumber(f64);
#[derive(Debug, FromForm)]
struct User {
id: i32,
number: NonZeroNumber,
}
#[get("/?<user..>")]
fn index(user: User) -> String {
format!("{:?}", user)
}
如上程式,我們也許會想要讓User
實體中的number
欄位允許錯誤,並在程式中判斷是什麼樣的錯誤來決定後續的行為。那麼我們可以把以上程式改成以下這個樣子:
use rocket::{FromForm, get};
use validators::prelude::*;
#[derive(Debug, Validator)]
#[validator(number(range(Outside(max = 0))))]
pub struct NonZeroNumber(f64);
#[derive(Debug, FromForm)]
struct User {
id: i32,
// number: Result<NonZeroNumber, validators::errors::NumberError>, // compile error
number: validators::Result<NonZeroNumber, validators::errors::NumberError>,
}
#[get("/?<user..>")]
fn index(user: User) -> String {
format!("{:?}", user)
}