Add email validation.

This commit is contained in:
LukeMathWalker 2020-12-28 12:26:05 +00:00
parent 837a4bcce9
commit f6d62fb7a1
6 changed files with 81 additions and 6 deletions

23
Cargo.lock generated
View file

@ -2646,6 +2646,28 @@ dependencies = [
"rand",
]
[[package]]
name = "validator"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d6937c33ec6039d8071bcf72933146b5bbe378d645d8fa59bdadabfc2a249"
dependencies = [
"idna",
"lazy_static",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_types",
]
[[package]]
name = "validator_types"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad9680608df133af2c1ddd5eaf1ddce91d60d61b6bc51494ef326458365a470a"
[[package]]
name = "vcpkg"
version = "0.2.10"
@ -2913,4 +2935,5 @@ dependencies = [
"tracing-subscriber",
"unicode-segmentation",
"uuid",
"validator",
]

View file

@ -29,6 +29,7 @@ tracing-log = "0.1.1"
tracing-actix-web = "0.2.0"
serde-aux = "1.0.1"
unicode-segmentation = "1.7.1"
validator = "0.12.0"
[dev-dependencies]
reqwest = { version = "0.10.7", features = ["json"] }

6
src/domain/mod.rs Normal file
View file

@ -0,0 +1,6 @@
mod subscriber_name;
mod subscriber_email;
mod new_subscriber;
pub use subscriber_name::SubscriberName;
pub use new_subscriber::NewSubscriber;

View file

@ -0,0 +1,6 @@
use crate::domain::subscriber_name::SubscriberName;
pub struct NewSubscriber {
pub email: String,
pub name: SubscriberName,
}

View file

@ -0,0 +1,44 @@
use validator::validate_email;
#[derive(Debug)]
pub struct SubscriberEmail(String);
impl SubscriberEmail {
pub fn parse(s: String) -> Result<SubscriberEmail, String> {
if validate_email(&s) {
Ok(Self(s))
} else {
Err(format!("{} is not a valid subscriber email.", s))
}
}
}
impl AsRef<str> for SubscriberEmail {
fn as_ref(&self) -> &str {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::SubscriberEmail;
use claim::assert_err;
#[test]
fn empty_string_is_rejected() {
let email = "".to_string();
assert_err!(SubscriberEmail::parse(email));
}
#[test]
fn email_missing_at_symbol_is_rejected() {
let email = "ursuladomain.com".to_string();
assert_err!(SubscriberEmail::parse(email));
}
#[test]
fn email_missing_subject_is_rejected() {
let email = "@domain.com".to_string();
assert_err!(SubscriberEmail::parse(email));
}
}

View file

@ -1,10 +1,5 @@
use unicode_segmentation::UnicodeSegmentation;
pub struct NewSubscriber {
pub email: String,
pub name: SubscriberName,
}
#[derive(Debug)]
pub struct SubscriberName(String);