Skip to content

Commit 5dd6267

Browse files
committed
impl Digit
1 parent 945402e commit 5dd6267

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/rule/string.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
mod alphabet;
2+
mod digit;
23
mod email;
34

45
pub use alphabet::{Alphabet, AlphabetRule};
6+
pub use digit::*;
57
pub use email::{Email, EmailRule};

src/rule/string/digit.rs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use crate::result::Error;
2+
use crate::rule::Rule;
3+
use crate::Refined;
4+
use regex::Regex;
5+
6+
pub type Digit = Refined<DigitRule>;
7+
pub struct DigitRule;
8+
9+
impl Rule for DigitRule {
10+
type Item = String;
11+
fn validate(target: Self::Item) -> Result<Self::Item, Error<Self::Item>> {
12+
let regex = Regex::new(r"[0-9]*").expect("Invalid regex");
13+
let is_valid = regex
14+
.find(target.as_str())
15+
.is_some_and(|matched| matched.as_str() == target.as_str());
16+
if is_valid {
17+
Ok(target)
18+
} else {
19+
Err(Error::new(
20+
"The input `String` have some digit characters",
21+
target,
22+
))
23+
}
24+
}
25+
}
26+
27+
#[cfg(test)]
28+
mod test {
29+
use crate::rule::string::digit::Digit;
30+
31+
#[test]
32+
fn test_digit_ok_1() {
33+
let digit = Digit::new("1234567890".to_string());
34+
assert!(digit.is_ok());
35+
}
36+
37+
#[test]
38+
fn test_digit_ok_2() {
39+
let digit = Digit::new("".to_string());
40+
assert!(digit.is_ok());
41+
}
42+
43+
#[test]
44+
fn test_digit_err() {
45+
let digit = Digit::new("1234567890abc".to_string());
46+
assert!(digit.is_err());
47+
}
48+
}

0 commit comments

Comments
 (0)