1 /*
2  * Hunt - A data validation for DLang based on hunt library.
3  *
4  * Copyright (C) 2015-2019, HuntLabs
5  *
6  * Website: https://www.huntlabs.net
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 module hunt.validation.validators.NotEmptyValidator;
12 
13 import hunt.validation.constraints.NotEmpty;
14 import hunt.validation.ConstraintValidator;
15 import hunt.validation.ConstraintValidatorContext;
16 import hunt.validation.Validator;
17 
18 import std.string;
19 import std.traits;
20 
21 class NotEmptyValidator(T) : AbstractValidator , ConstraintValidator!(NotEmpty, T) {
22 
23     private NotEmpty _notempty;
24 
25     override void initialize(NotEmpty constraintAnnotation){
26         _notempty = constraintAnnotation;
27     }
28     
29     override
30     public bool isValid(T data, ConstraintValidatorContext constraintValidatorContext) {
31         scope(exit) constraintValidatorContext.append(this);
32         
33         static if(is(T == class)) {
34             if(data is null)
35             {
36                 _isValid = false;
37                 return false;
38             }
39         }
40 
41         static if(isArray!(T) || isAssociativeArray!(T) || is(T == string))
42         {    
43             _isValid = data.strip().length > 0;
44             return _isValid;
45         } else static if(is(T == class)) {
46             if(data is null)
47             {
48                 _isValid = false;
49                 return false;
50             }
51         }
52         else 
53         {
54             static assert(false, "Unsupported type for NotEmptyValidator: " ~ T.stringof);
55         }
56 
57     }
58 
59     override string getMessage()
60     {
61         return _notempty.message;
62     }
63 }