1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
//! Validating Model fields for save and update.
use crate::{
store::{REGEX_IS_COLOR_CODE, REGEX_IS_DATE, REGEX_IS_DATETIME, REGEX_IS_PASSWORD},
widgets::Widget,
};
use mongodb::{
bson::{doc, oid::ObjectId, Bson},
sync::Collection,
};
use std::{collections::HashMap, error::Error};
/// Validating Model fields for save and update.
// *************************************************************************************************
pub trait ValidationModel {
/// Validation of `minlength`.
// ---------------------------------------------------------------------------------------------
fn check_minlength(minlength: usize, value: &str) -> Result<(), Box<dyn Error>> {
if minlength > 0 && value.encode_utf16().count() < minlength {
Err(format!("Exceeds limit, minlength={}.", minlength))?
}
Ok(())
}
/// Validation of `maxlength`.
// ---------------------------------------------------------------------------------------------
fn check_maxlength(maxlength: usize, value: &str) -> Result<(), Box<dyn Error>> {
if maxlength > 0 && value.encode_utf16().count() > maxlength {
Err(format!("Exceeds limit, maxlength={}.", maxlength))?
}
Ok(())
}
/// Accumulation of errors.
// ---------------------------------------------------------------------------------------------
fn accumula_err(widget: &Widget, err: &String) -> Result<String, Box<dyn Error>> {
let mut tmp = widget.error.clone();
tmp = if !tmp.is_empty() {
format!("{}<br>", tmp)
} else {
String::new()
};
Ok(format!("{}{}", tmp, err))
}
/// Validation in regular expression (email, password, etc...).
// ---------------------------------------------------------------------------------------------
fn regex_validation(field_type: &str, value: &str) -> Result<(), Box<dyn Error>> {
match field_type {
"inputEmail" => {
if !validator::validate_email(value) {
Err("Invalid email address.")?
}
}
"inputColor" => {
if !REGEX_IS_COLOR_CODE.is_match(value) {
Err("Invalid Color code.")?
}
}
"inputUrl" => {
if !validator::validate_url(value) {
Err("Invalid Url.")?
}
}
"inputIP" => {
if !validator::validate_ip(value) {
Err("Invalid IP address.")?
}
}
"inputIPv4" => {
if !validator::validate_ip_v4(value) {
Err("Invalid IPv4 address.")?
}
}
"inputIPv6" => {
if !validator::validate_ip_v6(value) {
Err("Invalid IPv6 address.")?
}
}
"inputPassword" => {
if !REGEX_IS_PASSWORD.is_match(value) {
Err("Size 8-256 chars.<br>\
Allowed chars: a-z A-Z 0-9 @ # $ % ^ & + = * ! ~ ) (")?
}
}
"inputDate" => {
if !REGEX_IS_DATE.is_match(value) {
Err("Incorrect date format.<br>\
Example: 1970-02-28")?
}
}
"inputDateTime" => {
if !REGEX_IS_DATETIME.is_match(value) {
Err("Incorrect date and time format.<br>\
Example: 1970-02-28T00:00")?
}
}
_ => return Ok(()),
}
Ok(())
}
/// Validation of `unique`.
// ---------------------------------------------------------------------------------------------
fn check_unique(
hash: &str,
field_name: &str,
bson_field_value: &Bson,
coll: &Collection,
) -> Result<(), Box<dyn Error>> {
//
let object_id = ObjectId::with_string(hash);
let mut filter = doc! { field_name: bson_field_value };
if let Ok(id) = object_id {
// If the document is will updated.
filter = doc! {
"$and": [
{ "_id": { "$ne": id } },
filter
]
};
}
let count: i64 = coll.count_documents(filter, None)?;
if count > 0 {
Err("Is not unique.")?
}
Ok(())
}
}
/// Methods for additional validation.
/// Hint: For custom use, add the Model/Form attribute `is_use_add_valid = true`.
/// Hint (for models): Remember to use for validate of ignored fields.
// *************************************************************************************************
///
/// # Example:
///
/// ```
/// impl AdditionalValidation for UserProfile {
/// fn add_validation<'a>(
/// &self,
/// ) -> Result<std::collections::HashMap<&'a str, &'a str>, Box<dyn std::error::Error>> {
/// // Hint: error_map.insert("field_name", "Error message.")
/// let mut error_map: std::collections::HashMap<&'a str, &'a str> =
/// std::collections::HashMap::new();
///
/// // Get clean data
/// let hash = self.hash.clone().unwrap_or_default();
/// let password = self.password.clone().unwrap_or_default();
/// let confirm_password = self.confirm_password.clone().unwrap_or_default();
/// let username = self.username.clone().unwrap_or_default();
///
/// // Fields validation
/// if hash.is_empty() && password != confirm_password {
/// error_map.insert("confirm_password", "Password confirmation does not match.");
/// }
/// if !RegexBuilder::new(r"^[a-z\d_@+.]+$")
/// .case_insensitive(true)
/// .build()
/// .unwrap()
/// .is_match(username.as_str())
/// {
/// error_map.insert(
/// "username",
/// "Invalid characters present.<br>\
/// Valid characters: a-z A-Z 0-9 _ @ + .",
/// );
/// }
///
/// Ok(error_map)
/// }
/// }
/// ```
///
pub trait AdditionalValidation {
// Default implementation as a stub.
fn add_validation<'a>(&self) -> Result<HashMap<&'a str, &'a str>, Box<dyn Error>> {
// error_map.insert("field_name", "Error message.")
let error_map: HashMap<&'a str, &'a str> = HashMap::new();
Ok(error_map)
}
}