5. Validation

DOGs comes with a set of default validators:

@validated

Requires the annotated field to also validate its properties. By default only the properties of the root object are validated.

Optional/Nullable fields are (for included validators) valid if they are null.

To use these validators, import package:dogs_core/dogs_validation.dart to the file containing your model.

Validators can be applied to fields by using them as annotations:

@serializable
class User {  
  @positive // Only ids >=0 are allowed.
  int id;
  
  String name;

  @SizeRange(min: 0, max: 16) // Must only have at max 16 claims
  @Minimum(1) // All claims must be >=1
  List<int>? claims;

  @polymorphic // This is not a validator
  Object? attachment;

  Note(this.text, this.id, this.attachment, this.claims);
}

An instance of the previous type can then be validated using the generated extensions on User:

User user = [...];
bool valid = user.isValid; // Returns if the user is valid
user.validate(); // Throws an exception if the user is invalid.

Validation can also be done without using generated extensions:

User user = [...];
bool valid = dogs.validateObject(user, User); // Returns if the user is valid
dogs.validate<User>(user);  // Throws an exception if the user is invalid.

Last updated