size function

bool size(
  1. dynamic property,
  2. ConstraintValidatorContext cvc
)

Implementation

bool size(dynamic property, ConstraintValidatorContext cvc) {
  if (cvc.parent is! Size) {
    throw StateError(
      'size validation called inside a non Size annotation (@Size)',
    );
  }
  Size rawAnnotation = cvc.parent as Size;
  if (rawAnnotation.min > rawAnnotation.max) {
    throw StateError('Min size must be less than Max (min <= max)');
  }

  int length = 0;
  String type = '';
  if (property == null) {
    if (!rawAnnotation.validOnNull) {
      cvc.addTemplateViolation('Property can\'t be null');
    }
  } else if (property is String) {
    length = property.length;
    type = 'Text';
  } else if (property is List) {
    length = property.length;
    type = 'List';
  } else if (property is Map) {
    length = property.length;
    type = 'Map';
  } else if (property is Set) {
    length = property.length;
    type = 'Set';
  }

  if (length < rawAnnotation.min) {
    cvc.addTemplateViolation(
      '$type length must be greater than ${rawAnnotation.min}',
    );
  }
  if (length > rawAnnotation.max) {
    cvc.addTemplateViolation(
      '$type length must be less than ${rawAnnotation.max}',
    );
  }
  return cvc.isValid();
}