validator method

dynamic validator({
  1. required Map<String, String> rules,
  2. required Map<String, dynamic> data,
  3. Map<String, dynamic> messages = const {},
  4. bool showAlert = true,
  5. Duration? alertDuration,
  6. ToastNotificationStyleType alertStyle = ToastNotificationStyleType.WARNING,
})

This validator method provides an easy way to validate data. You can use this method like the example below: try { this.validator(rules: { "email": "email|max:20", "name": "min:10" }, data: { "email": _textEditingEmailController.text, "name": _textEditingNameController.text });

} on ValidationException catch (e) { print(e.validationRule.description); print(e.toString()); } See more https://nylo.dev/docs/2.x/validation

Implementation

validator(
    {required Map<String, String> rules,
    required Map<String, dynamic> data,
    Map<String, dynamic> messages = const {},
    bool showAlert = true,
    Duration? alertDuration,
    ToastNotificationStyleType alertStyle =
        ToastNotificationStyleType.WARNING}) {
  Map<String, Map<String, dynamic>> map = data.map((key, value) {
    if (!rules.containsKey(key)) {
      throw new Exception('Missing rule: ' + key);
    }
    Map<String, dynamic> tmp = {"data": value, "rule": rules[key]};
    if (messages.containsKey(key)) {
      tmp.addAll({"message": messages[key]});
    }
    return MapEntry(key, tmp);
  });

  for (int i = 0; i < map.length; i++) {
    String attribute = map.keys.toList()[i];
    Map<String, dynamic> info = map[attribute]!;

    dynamic data = info['data'];

    String rule = info['rule'];
    List<String> rules = rule.split("|").toList();

    if (rule.contains("nullable") && (data == null || data == "")) {
      continue;
    }

    List<ValidationRule?> validationRules = [
      EmailRule(attribute),
      BooleanRule(attribute),
      ContainsRule(attribute),
      URLRule(attribute),
      StringRule(attribute),
      MaxRule(attribute),
      MinRule(attribute),
    ];

    for (rule in rules) {
      ValidationRule? validationRule =
          validationRules.firstWhere((validationRule) {
        if (validationRule!.signature == rule) {
          return true;
        }
        if (rule.contains(":")) {
          String firstSection = rule.split(":").first;
          return validationRule.signature == firstSection;
        }
        return false;
      }, orElse: () => null);
      if (validationRule == null) {
        continue;
      }
      bool hasFailed = validationRule.handle(info);
      if (hasFailed == false) {
        if (showAlert == true) {
          validationRule.alert(context,
              style: alertStyle, duration: alertDuration);
        }
        throw new ValidationException(attribute, validationRule);
      }
    }
  }
}