convert static method

Validator? convert(
  1. Map<String, dynamic> map
)

Convert a Map to a Validator, there are only one element in Map. Use 'all' or 'least' to combine multi validators.

Map key is a Validator name has been registered

Map value can be

  • null, empty, false: is skipped
  • true: use Validator with default values
  • String: use Validator with custom message
  • Map: contains key, value corresponding with properties of Validator

Implementation

static Validator? convert(Map<String, dynamic> map) {
  if (map.isEmpty) return null;
  if (map.keys.length > 1) {
    throw 'Map should has one element. '
        "Use 'all' or 'least' to combine multi validators";
  }
  var k = map.keys.first;
  var v = map[k];
  if (v == null || v.toString().isEmpty || (v is bool && !v)) return null;

  var type = registered[k];
  if (type == null) throw "Not found registered Validator for '$k'";

  var vd = type.creator();
  if (v is bool) {
    //nothing, because it's true now
  } else if (v is String) {
    vd.message = v;
  } else if (v is Map<String, dynamic>) {
    v.forEach((key, value) {
      switch (key) {
        case 'message':
        case 'msg':
          vd.message = value.toString();
          break;
        case 'condition':
        case 'if':
          if (value is! bool Function()) {
            throw "The value of '$key' should be Function";
          }
          vd.condition = value;
          break;
        default:
          if (type.mapping != null) type.mapping!(vd, key, value);
      }
    });
  } else {
    throw 'Map value should be bool, String, Map';
  }
  return vd;
}