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.SizeValidator; 12 13 import hunt.validation.constraints.Size; 14 import hunt.validation.ConstraintValidator; 15 import hunt.validation.ConstraintValidatorContext; 16 import std.exception; 17 import hunt.validation.Validator; 18 19 import hunt.logging; 20 import std.string; 21 22 public class SizeValidator(T) : AbstractValidator , ConstraintValidator!(Size, T) { 23 24 private Size _size; 25 26 override void initialize(Size constraintAnnotation){ 27 _size = constraintAnnotation; 28 } 29 30 override 31 public bool isValid(T data, ConstraintValidatorContext constraintValidatorContext) { 32 scope(exit) constraintValidatorContext.append(this); 33 34 static if(isArray!(T) || isAssociativeArray!(T)) 35 { 36 if( data.length < _size.min || data.length > _size.max) 37 { 38 _isValid = false; 39 } 40 else 41 { 42 _isValid = true; 43 } 44 return _isValid; 45 } 46 else 47 { 48 throw new Exception("not support type : ",T.stringof); 49 _isValid = false; 50 return false; 51 } 52 53 } 54 55 override string getMessage() 56 { 57 import hunt.text.FormatterWrapper; 58 import hunt.util.Serialize; 59 60 return new FormatterWrapper("{{","}}").format(_size.message,toJSON(_size)); 61 } 62 }