buildValidator method

String buildValidator(
  1. List? validators, {
  2. bool functionOnly = false,
})

Implementation

String buildValidator(List? validators, {bool functionOnly = false}) {
  // ignore: avoid_annotating_with_dynamic
  dynamic _quoteIfNeeded(dynamic value) {
    if (value?.runtimeType.toString() == 'String') {
      if (RegExp(r'^".*"$').hasMatch(value as String)) {
        return value;
      }
      return '\"$value\"';
    }
    return value;
  }

  final validatorList = <String>[];
  final List<String> customFunctions = [];

  if (validators == null || validators.isEmpty) {
    return '';
  }
  for (final validator in validators) {
    final args = validator[validator.keys.first];
    if (args is! Map) {
      throw Exception('Args is not a map: $args');
    }
    //  print('validator:' + validator.toString());
    final String? customFunction = args.remove('function') as String?;
    final argList = args.keys.map((key) => '$key: ${_quoteIfNeeded(args[key])}').join(',');
    if (validator.keys.first == 'custom') {
      if (customFunction == null || customFunction.trim().isEmpty || !customFunction.startsWith('custom(String? value')) {
        throw Exception('You must specify a function to validate the field.\n$customFunction');
      }
      try {
        customFunction.replaceAll('custom(String?', '_custom${customFunctions.length}(String?');
        customFunctions.add(DartFormatter().format('$customFunction'));
      } catch (e) {
        throw Exception('You must specify a valid function to validate the field.\n$customFunction');
      }
      for (int index = 0; index < customFunctions.length; index++) {
        validatorList.add('result = _custom${index}(value, $argList);');
      }
    } else {
      //  print('argList: $argList');
      validatorList.add('result = FormValidator.${validator.keys.first}(value, $argList);\n');
    }
    validatorList.add('''
      if (result != null) {
        errorList.add(result);
      }
    ''');
  }
  final result = '''
   ${functionOnly ? 'String? validator' : 'validator:'} (value) {
      final errorList = <String>[];
      String? result;
      ${customFunctions.join('\n')}
      ${validatorList.join('\n')}
      return errorList.isEmpty ? null : errorList.join('\\n');
    ${functionOnly ? '}' : '},'}
  ''';
  return result;
}