validateField method

void validateField(
  1. Field field
)

Implementation

void validateField(Field field) {
  // Only validate if field is touched or form is submitted
  if (touched[field.name] != true && !submitted) {
    return;
  }

  String? errorMessage;
  final value = values[field.name];
  final validation = field.validation;

  if (validation != null) {
    // Array validation (for checkbox groups, etc)
    bool isRequired = selectIsFieldRequired(field);
    // debugPrint(
    //     'Required ${isRequired} Field: ${field.name} value: $value runtimeType: ${value.runtimeType} field type: ${field.fieldType}');

    if (value is List && value.isEmpty) {
      errorMessage =
          validation.message ?? 'Please select at least one ${field.name}';
    } else if (isRequired == true &&
        ((field.fieldType == 'month' || field.fieldType == 'checkbox') &&
            ((value is String && value.isEmpty) ||
                value == 'null' ||
                value == null ||
                value == 0 ||
                value == 0.0 ||
                value == '0' ||
                value == '0.00'))) {
      errorMessage = validation.message ?? '${field.label} is required';
    } else if (isRequired == true &&
        (value == 'null' || value == null || value == '' || value == 0)) {
      errorMessage = validation.message ?? '${field.label} is required';
    }

    // Only continue with other validations if there's a value
    if (value != null && value.toString().isNotEmpty) {
      // Conditional validation
      if (validation.conditionalOn != null) {
        final condition = validation.conditionalOn!;
        final conditionValue = values[condition.field];

        if (condition.values.contains(conditionValue)) {
          if (condition.regex != null && value != null) {
            final pattern = RegExp(condition.regex!.pattern);
            if (!pattern.hasMatch(value.toString())) {
              errorMessage =
                  condition.regex!.message ?? '${field.label} is not valid';
            }
          } else if (value == null || (value is List && value.isEmpty)) {
            errorMessage = validation.message ?? '${field.label} is required';
          }
        }
      }
      // Regular regex validation
      else if (validation.regex != null) {
        final pattern = RegExp(validation.regex!.pattern);
        if (!pattern.hasMatch(value.toString())) {
          errorMessage =
              validation.regex!.message ?? '${field.label} is not valid';
        }
      }

      // Length validations
      if (value is String || value is List) {
        if (validation.minLength != null &&
            value.length < validation.minLength!) {
          errorMessage = validation.message ??
              '${field.label} must be at least ${validation.minLength} characters';
        }
        if (validation.maxLength != null &&
            value.length > validation.maxLength!) {
          errorMessage = validation.message ??
              '${field.label} must not exceed ${validation.maxLength} characters';
        }
      }

      // Min/Max validations with template support
      var min = validation.min;
      var max = validation.max;

      // Replace template variables in min/max
      if (min != null || max != null) {
        values.forEach((key, val) {
          if (min?.contains('{{$key}}') == true) {
            min = min!.replaceAll('{{$key}}', val.toString());
          }
          if (max?.contains('{{$key}}') == true) {
            max = max!.replaceAll('{{$key}}', val.toString());
          }
        });
      }

      // Numeric validations
      if (value is num ||
          (value is String && double.tryParse(value) != null)) {
        final numValue = value is num ? value : double.parse(value);

        if (min != null && numValue < double.parse(min!)) {
          final errorData = field.fieldType == 'month'
              ? formatMonthsToYearsAndMonths(double.parse(min!))
              : formatAmount(double.parse(min!));
          errorMessage = validation.message ??
              '${field.label} must be at least $errorData';
        }

        if (max != null && numValue > double.parse(max!)) {
          final errorData = field.fieldType == 'month'
              ? formatMonthsToYearsAndMonths(double.parse(max!))
              : formatAmount(double.parse(max!));
          errorMessage = validation.message ??
              '${field.label} must not exceed $errorData';
        }
      }
    }
  }

  // Update error state
  if (errorMessage != null) {
    errors[field.name] = errorMessage;
  } else {
    errors.remove(field.name);
  }
}