validateValue method

EntityFieldInvalid? validateValue(
  1. Object? value, {
  2. String? fieldName,
  3. Type? entityType,
})

Returns a EntityFieldInvalid if value is invalid for this EntityField configuration.

Implementation

EntityFieldInvalid? validateValue(Object? value,
    {String? fieldName, Type? entityType}) {
  var validator = this.validator;
  if (validator != null) {
    if (!validator(value)) {
      return EntityFieldInvalid('validator', value,
          fieldName: fieldName, entityType: entityType);
    }
  }

  var regexp = this.regexp;
  if (regexp != null) {
    var s = value == null ? '' : value.toString();

    var re = RegExp(regexp, dotAll: true);
    var valid = re.hasMatch(s);

    if (!valid) {
      return EntityFieldInvalid('regexp(${re.pattern})', value,
          entityType: entityType, fieldName: fieldName);
    }
  }

  if (value != null) {
    var maximum = this.maximum;

    if (maximum != null) {
      var invalid = false;
      String? valueStr;

      if (value is num) {
        if (value > maximum) invalid = true;
      } else if (value is BigInt) {
        if (value > maximum.toBigInt()) invalid = true;
      } else if (value is DynamicNumber) {
        if (value > maximum.toDynamicNumber()) invalid = true;
      } else if (value is String) {
        if (value.length > maximum) invalid = true;
      } else if (value is Iterable) {
        if (value.length > maximum) {
          invalid = true;
          valueStr = '${value.runtimeTypeNameUnsafe}{length: ${value.length}';
        }
      }

      if (invalid) {
        valueStr ??= '$value';
        return EntityFieldInvalid('maximum($maximum)', value,
            entityType: entityType, fieldName: fieldName);
      }
    }

    var minimum = this.minimum;
    if (minimum != null) {
      var invalid = false;
      String? valueStr;

      if (value is num) {
        if (value < minimum) invalid = true;
      } else if (value is BigInt) {
        if (value < minimum.toBigInt()) invalid = true;
      } else if (value is DynamicNumber) {
        if (value < minimum.toDynamicNumber()) invalid = true;
      } else if (value is String) {
        if (value.length < minimum) invalid = true;
      } else if (value is Iterable) {
        if (value.length < minimum) {
          invalid = true;
          valueStr = '${value.runtimeTypeNameUnsafe}{length: ${value.length}';
        }
      }

      if (invalid) {
        valueStr ??= '$value';
        return EntityFieldInvalid('minimum($minimum)', value,
            entityType: entityType, fieldName: fieldName);
      }
    }
  }

  return null;
}