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.digit; 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.ascii; 18 import std.stdio; 19 import std.conv; 20 21 /** 22 * Checks if a value has a correct e-mail format 23 24 * Check Unittests for examples at the bottom of the file. 25 */ 26 struct DigitOptions 27 { 28 string label; 29 bool allowEmpty = false; 30 string message; 31 } 32 33 class Digit : Validator 34 { 35 36 protected DigitOptions _options; 37 38 /** 39 * constructor 40 */ 41 this(DigitOptions options) 42 { 43 this._options = options; 44 } 45 46 bool validate(string field = null) 47 { 48 bool valid = false; 49 string value = field; 50 51 if (this._options.allowEmpty && value.length == 0) { 52 return true; 53 } 54 55 return isNumeric(value); 56 } 57 58 59 /** 60 * Executes the validation 61 */ 62 override bool validate(Validation validation, string field = null) 63 { 64 string value = validation.getValue(field); 65 66 if (this._options.allowEmpty && value.length == 0) { 67 return true; 68 } 69 70 if (!isNumeric(value)) { 71 72 string label = (this._options.label.length == 0) 73 ? validation.getLabel(field) 74 : this._options.label; 75 76 string message = this._options.message; 77 78 if (message.length == 0) { 79 message = validation.getDefaultMessage("Digit"); 80 } 81 82 validation.appendMessage(new Message(format(message, label), field, "Digit")); 83 return false; 84 } 85 86 return true; 87 } 88 89 } 90 91 unittest 92 { 93 // WITH VALIDATOR 94 95 auto validation = new Validation(); 96 97 auto options = DigitOptions(); 98 99 Digit test = new Digit(options); 100 assert(test.validate(validation, "test") == false); 101 assert(test.validate(validation, "1") == true); 102 103 test = new Digit(options); 104 assert(test.validate("jorgefaianca@gmail.") == false); 105 assert(test.validate("123213123") == true); 106 assert(test.validate(validation, "321.23") == true); 107 108 }