entityId method

ValidatorBuilder entityId(
  1. String field,
  2. String? value,
  3. String prefix, {
  4. bool required = false,
})

Entity ID validation convenience method

Implementation

ValidatorBuilder entityId(
  String field,
  String? value,
  String prefix, {
  bool required = false,
}) {
  final fullField = _prefix != null ? '$_prefix.$field' : field;

  _schema['properties'][field] = {
    'type': 'string',
    if (required) 'required': true,
    'pattern':
        r'^[0-9a-f]{4}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
  };

  if (required && (value == null || value.isEmpty)) {
    _errors.add(ValidationError('$fullField is required'));
  } else if (value != null && value.isNotEmpty) {
    final entityIdRegex = RegExp(
      r'^[0-9a-f]{4}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
    );
    if (!entityIdRegex.hasMatch(value.toLowerCase())) {
      _errors.add(
        ValidationError(
          '$fullField must be in format xxxx-{uuid} where xxxx is a 4-lowercase-hex-character prefix',
        ),
      );
    } else if (!value.toLowerCase().startsWith('${prefix.toLowerCase()}-')) {
      _errors.add(
        ValidationError('$fullField must start with prefix $prefix'),
      );
    }
  }

  return this;
}