validateAndForm method

Future<({Map<String, dynamic> form, bool result})> validateAndForm({
  1. Map data = const {},
})

Validates the form data and returns both the result and the validated form structure.

The validated form structure contains information about the validation results, including error messages, the validity state, and field values.

If data is provided, it will be used instead of loading data from the request.

Returns a tuple containing:

  • result: The overall validation result (true if all validations pass).
  • form: A map of the form structure containing field validation details.

Implementation

Future<({bool result, Map<String, dynamic> form})> validateAndForm({
  Map data = const {},
}) async {
  bool result = true;
  var thisForm = <String, dynamic>{};

  for (var fieldName in fields.keys) {
    var fieldResult = <String, dynamic>{};
    Object fieldValue;
    if (data.isEmpty) {
      fieldValue = rq.data(fieldName);
    } else {
      fieldValue = data[fieldName] ?? extraData[fieldName];
    }

    fieldResult["value"] = fieldValue;

    var fieldEvents = fields[fieldName] ?? [];

    var success = true;
    var errors = [];
    for (var validateField in fieldEvents) {
      FieldValidateResult check = validateField(fieldValue);
      if (!check.success) {
        success = false;
      }

      errors.addAll(check.errors);
    }

    fieldResult['valid'] = success ? this.success : failed;
    fieldResult['error'] = errors.join(',');
    fieldResult['errorHtml'] = errors.join('<br/>');
    fieldResult['errors'] = errors;
    fieldResult['success'] = success;
    fieldResult['failed'] = !success;
    if (!success) {
      result = false;
    }

    thisForm[fieldName] = fieldResult;
  }

  extraData.forEach((key, value) {
    if (!thisForm.containsKey(key)) {
      thisForm[key] = {
        'success': true,
        'failed': false,
        'error': '',
        'errors': [],
        'errorHtml': '',
        'valid': success,
        'value': value,
      };
    }
  });

  rq.addValidator(name, thisForm);

  return (result: result, form: thisForm);
}