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.alpha;
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 
20 /**
21  * Check for alphabetic character(s)
22 
23  * Check Unittests for examples at the bottom of the file.
24  */
25 struct AlphaOptions
26 {
27 	string label;
28 	bool allowEmpty = false;
29 	string message;
30 }
31 
32 class Alpha : Validator
33 {
34 
35 	protected AlphaOptions _options;
36 
37 	/**
38 	 * constructor
39 	 */
40 	this(AlphaOptions 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 all!isAlpha(value);
55 	}
56 
57 
58 	/**
59 	*  For the form component
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 (!all!isAlpha(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("Alpha");
80 			}
81 
82 			validation.appendMessage(new Message(format(message, label), field, "Alpha"));
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 = AlphaOptions();
98 
99 	Alpha test = new Alpha(options);
100 	assert(test.validate(validation, "test") == true);
101 	assert(test.validate(validation, "1") == false);
102 
103 	test = new Alpha(options);
104 	assert(test.validate("jorgefaiancagmail") == true);
105 	assert(test.validate("123213123") == false);
106 	assert(test.validate(validation, "321.23") == false);
107 
108 }