5. Validation
DOGs comes with a set of default validators:
@LengthRange()
Specify upper and lower bounds for the string length using the min and max properties.
@Regex()
Specify a regex that the string will be matched against. The string is deemed invalid if it doesn't fully match the regex.
@email
Requires a valid email address as per a reduced form of RFC 5322 where ip addresses, double quotes and square brackets are omitted.
@notBlank
Requires a string that not only consists of whitespace.
@Range()
Specify upper and lower bounds for the number using the min and max properties. The exclusiveness of the range can be specified by the corresponding properties.
@Minimum()
Defines a lower bound for the number. The exclusiveness can be configured using minExclusive-
@Maximum()
Defines a upper bound for the number. The exclusiveness can be configured using maxExclusive.
@postive
Requires numbers to be greater than zero.
@positiveOrZero
Requires numbers to be greater or equal to zero.
@negative
Requires numbers to be smaller than zero.
@negativeOrZero
Requires numbers to be smaller or equal to zero.
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