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.range;
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.algorithm;
19 import std.conv;
20 import std.stdio;
21 
22 /**
23  * Check for alphabetic character(s)
24 
25  * Check Unittests for examples at the bottom of the file.
26  */
27 struct RangeOptions
28 {
29 	int min;
30 	int max;
31 	string label;
32 	bool allowEmpty = false;
33 	string message;
34 }
35 
36 class Range : Validator
37 {
38 
39 	protected RangeOptions _options;
40 
41 	/**
42 	 * constructor
43 	 */
44 	this(RangeOptions options)
45 	{
46 		this._options = options;
47 	}
48 
49 	bool validate(string field = null)
50 	{
51 		bool valid = false;
52 
53 		if (this._options.allowEmpty && field.length == 0) {
54 			return true;
55 		}
56 
57 		int value = to!(int)(field);
58 
59 		if (!this._options.min || !this._options.max) {
60 			throw new Exception("A minimum and a maximum must be set.");
61 		}
62 
63 		if (value < this._options.min || value > this._options.max) {
64 			return false;
65 		}
66 
67 		return true;
68 	}
69 
70 
71 	/**
72 	*  For the form component
73 	 * Executes the validation
74 	 */
75 	override bool validate(Validation validation, string field = null)
76 	{
77 		bool valid = false;
78 
79 		if (this._options.allowEmpty && validation.getValue(field).length == 0) {
80 			return true;
81 		}
82 
83 		int value = to!(int)(validation.getValue(field));
84 
85 		if (!this._options.min || !this._options.max) {
86 			throw new Exception("A minimum and a maximum must be set.");
87 		}
88 
89 		if (value < this._options.min || value > this._options.max) {
90 
91 			string label = (this._options.label.length == 0)
92 							? validation.getLabel(field)
93 							: this._options.label;
94 
95 			string message = this._options.message;
96 
97 			if (message.length == 0) {
98 				message = validation.getDefaultMessage("Range");
99 			}
100 
101 			validation.appendMessage(new Message(format(message, label, this._options.min, this._options.max), field, "Range"));
102 			return false;
103 		}
104 
105 		return true;
106 	}
107 
108 }
109 
110 unittest
111 {
112 	// WITH VALIDATOR
113 	auto validation = new Validation();
114 
115 	auto options = RangeOptions();
116 		options.min = 10;
117 		options.max = 15;
118 
119 	Range test = new Range(options);
120 	assert(test.validate(validation, "11") == true);
121 	assert(test.validate(validation, "12") == true);
122 	assert(test.validate("9") == false);
123 	assert(test.validate("16") == false);
124 
125 }