/src/validators/string_validators.rs

https://github.com/async-graphql/async-graphql · Rust · 104 lines · 87 code · 10 blank · 7 comment · 24 complexity · 16911c9a1059b3561f2a90c3f6a2be0f MD5 · raw file

  1. use crate::validators::InputValueValidator;
  2. use crate::Value;
  3. use once_cell::sync::Lazy;
  4. use regex::Regex;
  5. /// String minimum length validator
  6. pub struct StringMinLength {
  7. /// Must be greater than or equal to this value.
  8. pub length: i32,
  9. }
  10. impl InputValueValidator for StringMinLength {
  11. fn is_valid(&self, value: &Value) -> Result<(), String> {
  12. if let Value::String(s) = value {
  13. if s.len() < self.length as usize {
  14. Err(format!(
  15. "the value length is {}, must be greater than or equal to {}",
  16. s.len(),
  17. self.length
  18. ))
  19. } else {
  20. Ok(())
  21. }
  22. } else {
  23. Ok(())
  24. }
  25. }
  26. }
  27. /// String maximum length validator
  28. pub struct StringMaxLength {
  29. /// Must be less than or equal to this value.
  30. pub length: i32,
  31. }
  32. impl InputValueValidator for StringMaxLength {
  33. fn is_valid(&self, value: &Value) -> Result<(), String> {
  34. if let Value::String(s) = value {
  35. if s.len() > self.length as usize {
  36. Err(format!(
  37. "the value length is {}, must be less than or equal to {}",
  38. s.len(),
  39. self.length
  40. ))
  41. } else {
  42. Ok(())
  43. }
  44. } else {
  45. Ok(())
  46. }
  47. }
  48. }
  49. static EMAIL_RE: Lazy<Regex> = Lazy::new(|| {
  50. Regex::new("^(([0-9A-Za-z!#$%&'*+-/=?^_`{|}~&&[^@]]+)|(\"([0-9A-Za-z!#$%&'*+-/=?^_`{|}~ \"(),:;<>@\\[\\\\\\]]+)\"))@").unwrap()
  51. });
  52. /// Email validator
  53. pub struct Email {}
  54. impl InputValueValidator for Email {
  55. fn is_valid(&self, value: &Value) -> Result<(), String> {
  56. if let Value::String(s) = value {
  57. if !EMAIL_RE.is_match(s) {
  58. Err("invalid email format".to_string())
  59. } else {
  60. Ok(())
  61. }
  62. } else {
  63. Ok(())
  64. }
  65. }
  66. }
  67. static MAC_ADDRESS_RE: Lazy<Regex> =
  68. Lazy::new(|| Regex::new("^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$").unwrap());
  69. static MAC_ADDRESS_NO_COLON_RE: Lazy<Regex> =
  70. Lazy::new(|| Regex::new("^[0-9a-fA-F]{12}$").unwrap());
  71. /// MAC address validator
  72. pub struct MAC {
  73. /// Must include colon.
  74. pub colon: bool,
  75. }
  76. impl InputValueValidator for MAC {
  77. fn is_valid(&self, value: &Value) -> Result<(), String> {
  78. if let Value::String(s) = value {
  79. if self.colon {
  80. if !MAC_ADDRESS_RE.is_match(s) {
  81. Err("invalid MAC format".to_string())
  82. } else {
  83. Ok(())
  84. }
  85. } else if !MAC_ADDRESS_NO_COLON_RE.is_match(s) {
  86. Err("invalid MAC format".to_string())
  87. } else {
  88. Ok(())
  89. }
  90. } else {
  91. Ok(())
  92. }
  93. }
  94. }