Hello
I have a simple function taking a three parameters. I want to input-validate these parameters.
This is my current approach:
/*
Method to send a text-message
:param to: Telephone number to send message to. Format: +xx.xxxxxxxxx
:param from: Source of message. Format: +xx.xxxxxxxxx
:param message: Content of message to send
:return Result<(), &str>: Returns Ok() if successfull. Returns an error otherwise.
*/
pub async fn send(&self, to: String, from: String, message: String) -> Result<(), &str> {
// Input validation
let phone_number_regex = Regex::new(r"\+\d{2,3}\.\d{7,12}").unwrap();
if message.len() == 0 {
return Err("Message cannot be empty.");
}
if message.len() > 160 {
return Err("Message cannot be more than 160 characters");
}
if !phone_number_regex.is_match(&to) || !phone_number_regex.is_match(&from) {
return Err(
"Phone numbers must be in the format: +xx.yyyyyyyyy where xx is the country code.",
);
}
//...
Ok(())
}
This is how I call it in my main.rs
:
let to = "".to_string();
let from = "".to_string();
let message = "test".to_string();
send(to, from, message).await.ok();
I basically want to check if the parameters pass some basic tests as not being empty, not being too long,... If a test fails I want to display an error and terminate the function. But I do NOT want to exit the whole program.
Also, currently when an error occurs the error-message is not outputted. How do I output the &str
the function returns if invalid parameters are given?
match tigron_sms.send(to, from, message).await {
Ok(_) => (),
Err(e) => println!("{}", e),
};
works. But I am searching for a shorter solution if that exists.
Anyway, how would I improve this code?