async-graphql/src/validators/string_validators.rs

106 lines
2.8 KiB
Rust
Raw Normal View History

2020-03-21 07:07:11 +00:00
use once_cell::sync::Lazy;
use regex::Regex;
2020-10-15 06:38:10 +00:00
use crate::validators::InputValueValidator;
use crate::Value;
2020-03-22 01:34:32 +00:00
/// String minimum length validator
pub struct StringMinLength {
/// Must be greater than or equal to this value.
pub length: i32,
2020-03-22 01:34:32 +00:00
}
impl InputValueValidator for StringMinLength {
fn is_valid(&self, value: &Value) -> Result<(), String> {
2020-03-22 01:34:32 +00:00
if let Value::String(s) = value {
if s.len() < self.length as usize {
Err(format!(
"the value length is {}, must be greater than or equal to {}",
2020-03-22 01:34:32 +00:00
s.len(),
self.length
))
} else {
Ok(())
2020-03-22 01:34:32 +00:00
}
} else {
Ok(())
2020-03-22 01:34:32 +00:00
}
}
}
/// String maximum length validator
pub struct StringMaxLength {
/// Must be less than or equal to this value.
pub length: i32,
2020-03-22 01:34:32 +00:00
}
impl InputValueValidator for StringMaxLength {
fn is_valid(&self, value: &Value) -> Result<(), String> {
2020-03-22 01:34:32 +00:00
if let Value::String(s) = value {
if s.len() > self.length as usize {
Err(format!(
"the value length is {}, must be less than or equal to {}",
2020-03-22 01:34:32 +00:00
s.len(),
self.length
))
} else {
Ok(())
2020-03-22 01:34:32 +00:00
}
} else {
Ok(())
2020-03-22 01:34:32 +00:00
}
}
}
2020-03-21 07:07:11 +00:00
static EMAIL_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new("^(([0-9A-Za-z!#$%&'*+-/=?^_`{|}~&&[^@]]+)|(\"([0-9A-Za-z!#$%&'*+-/=?^_`{|}~ \"(),:;<>@\\[\\\\\\]]+)\"))@").unwrap()
});
/// Email validator
pub struct Email {}
impl InputValueValidator for Email {
fn is_valid(&self, value: &Value) -> Result<(), String> {
2020-03-21 07:07:11 +00:00
if let Value::String(s) = value {
if !EMAIL_RE.is_match(s) {
Err("invalid email format".to_string())
2020-03-21 07:07:11 +00:00
} else {
Ok(())
2020-03-21 07:07:11 +00:00
}
} else {
Ok(())
2020-03-21 07:07:11 +00:00
}
}
}
static MAC_ADDRESS_RE: Lazy<Regex> =
Lazy::new(|| Regex::new("^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$").unwrap());
static MAC_ADDRESS_NO_COLON_RE: Lazy<Regex> =
Lazy::new(|| Regex::new("^[0-9a-fA-F]{12}$").unwrap());
/// MAC address validator
pub struct MAC {
2020-03-22 01:34:32 +00:00
/// Must include colon.
pub colon: bool,
2020-03-21 07:07:11 +00:00
}
impl InputValueValidator for MAC {
fn is_valid(&self, value: &Value) -> Result<(), String> {
2020-03-21 07:07:11 +00:00
if let Value::String(s) = value {
if self.colon {
if !MAC_ADDRESS_RE.is_match(s) {
Err("invalid MAC format".to_string())
2020-03-21 07:07:11 +00:00
} else {
Ok(())
2020-03-21 07:07:11 +00:00
}
} else if !MAC_ADDRESS_NO_COLON_RE.is_match(s) {
Err("invalid MAC format".to_string())
2020-03-21 07:07:11 +00:00
} else {
Ok(())
2020-03-21 07:07:11 +00:00
}
} else {
Ok(())
2020-03-21 07:07:11 +00:00
}
}
}