getField function

IValidator getField(
  1. String key,
  2. IValidator inner
)

Extracts and validates a field from a map.

Retrieves the value associated with the key from a map and passes it to the inner validator. Fails if the input is not a map or if the key is not present.

If you need to validate more than one field, consider using eskema.

Implementation

IValidator getField(String key, IValidator inner) {
  FutureOr<Result> fieldPredicate(value) {
    final result = inner.validate(value[key]);
    if (result.isValid) return result;

    return Result.invalid(
      value,
      expectations: result.expectations.map(
        (e) => Expectation(
          message: e.message,
          value: e.value,
          path: '$key${e.path != null ? '.${e.path}' : ''}',
        ),
      ),
    );
  }

  return isMap() & containsKey(key) & Validator(fieldPredicate);
}