1 /** 2 * Skadi.d Web Framework 3 * Validation Component 4 5 * Authors: Faianca 6 * Copyright: Copyright (c) 2015 Faianca 7 * License: MIT License, see LICENSE 8 */ 9 module skadi.components.validation.validators.email; 10 11 import skadi.components.validation.validatorInterface; 12 import skadi.components.validation.validation; 13 import skadi.components.validation.validator; 14 import skadi.components.validation.message; 15 16 import std..string; 17 import std.regex; 18 import std.stdio; 19 20 /** 21 * Checks if a value has a correct e-mail format 22 23 * Check Unittests for examples at the bottom of the file. 24 */ 25 struct EmailOptions 26 { 27 string label; 28 bool allowEmpty = false; 29 string message; 30 } 31 32 class Email : Validator 33 { 34 35 protected EmailOptions _options; 36 37 /** 38 * constructor 39 */ 40 this(EmailOptions options) 41 { 42 this._options = options; 43 } 44 45 bool validate(string field = null) 46 { 47 bool valid = false; 48 string value = field; 49 50 if (this._options.allowEmpty && value.length == 0) { 51 return true; 52 } 53 54 return this.validateEmail(value); 55 } 56 57 58 /** 59 * Executes the validation 60 */ 61 override bool validate(Validation validation, string field = null) 62 { 63 string value = validation.getValue(field); 64 65 if (this._options.allowEmpty && value.length == 0) { 66 return true; 67 } 68 69 if (!this.validateEmail(value)) { 70 71 string label = (this._options.label.length == 0) 72 ? validation.getLabel(field) 73 : this._options.label; 74 75 string message = this._options.message; 76 77 if (message.length == 0) { 78 message = validation.getDefaultMessage("Email"); 79 } 80 81 validation.appendMessage(new Message(format(message, label), field, "Email")); 82 return false; 83 } 84 85 return true; 86 } 87 88 /** 89 * Simple Regex 90 **/ 91 private bool validateEmail(string value) 92 { 93 auto t = match(value, regex(`(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)`)); 94 return !t.empty; 95 } 96 } 97 98 unittest 99 { 100 // WITH VALIDATOR 101 102 auto validation = new Validation(); 103 104 auto options = EmailOptions(); 105 106 Email test = new Email(options); 107 assert(test.validate(validation, "test") == false); 108 assert(test.validate(validation, "jorgefaianca@gmail.com") == true); 109 110 test = new Email(options); 111 assert(test.validate("jorgefaianca@gmail.") == false); 112 assert(test.validate("jorgefaianca.gmail.com") == false); 113 assert(test.validate(validation, "teste@test.com") == true); 114 115 }