extend method

Validator extend(
  1. Map<String, dynamic> schema,
  2. {Map<String, dynamic> defaultValues = const {},
  3. Map<String, dynamic> customErrorMessages = const {},
  4. bool overwrite = false}
)

Creates a copy with additional validation rules.

Implementation

Validator extend(Map<String, dynamic> schema,
    {Map<String, dynamic> defaultValues = const {},
    Map<String, dynamic> customErrorMessages = const {},
    bool overwrite = false}) {
  Map<String, dynamic> _schema = {};
  var child = Validator.empty()
    ..defaultValues.addAll(this.defaultValues)
    ..defaultValues.addAll(defaultValues ?? {})
    ..customErrorMessages.addAll(this.customErrorMessages)
    ..customErrorMessages.addAll(customErrorMessages ?? {})
    ..requiredFields.addAll(requiredFields)
    ..rules.addAll(rules);

  for (var key in schema.keys) {
    var fieldName = key.replaceAll(_asterisk, '').replaceAll(_forbidden, '').replaceAll(_optional, '');
    var isForbidden = _forbidden.hasMatch(key);
    var isOptional = _optional.hasMatch(key);
    var isRequired = _asterisk.hasMatch(key);

    if (isForbidden) {
      child
        ..requiredFields.remove(fieldName)
        ..forbiddenFields.add(fieldName);
    } else if (isOptional) {
      child..forbiddenFields.remove(fieldName)..requiredFields.remove(fieldName);
    } else if (isRequired) {
      child
        ..forbiddenFields.remove(fieldName)
        ..requiredFields.add(fieldName);
    }

    if (overwrite) {
      if (child.rules.containsKey(fieldName)) child.rules.remove(fieldName);
    }

    _schema[fieldName] = schema[key];
  }

  return child.._importSchema(_schema);
}