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.alphanum;
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 AlphaNumOptions
26 {
27 	string label;
28 	bool allowEmpty = false;
29 	string message;
30 }
31 
32 class AlphaNum : Validator
33 {
34 
35 	protected AlphaNumOptions _options;
36 
37 	/**
38 	 * constructor
39 	 */
40 	this(AlphaNumOptions 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!isAlphaNum(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 (!all!isAlphaNum(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("Alnum");
79 			}
80 
81 			validation.appendMessage(new Message(format(message, label), field, "Alnum"));
82 			return false;
83 		}
84 
85 		return true;
86 	}
87 
88 }
89 
90 unittest
91 {
92 	// WITH VALIDATOR
93 
94 	auto validation = new Validation();
95 
96 	auto options = AlphaNumOptions();
97 
98 	AlphaNum test = new AlphaNum(options);
99 	assert(test.validate(validation, "test") == true);
100 	assert(test.validate(validation, "1") == true);
101 	assert(test.validate(validation, "jorgefaiancag|@mail.comp") == false);
102 
103 	test = new AlphaNum(options);
104 	assert(test.validate("jorgefaiancagmail121323") == true);
105 	assert(test.validate("test.com") == false);
106 	assert(test.validate("123213123") == true);
107 	assert(test.validate(validation, "321.23") == false);
108 
109 }