Required static method
Returns a validator that checks if a string is empty.
Arguments :
errorMessage
: The error message to return if the string is empty.next
: A validator to run after this validator.
Usage :
TextFormField(
validator: Validators.Required(),
),
Usage without TextFormField :
final validator = Validators.Required();
validator(''); // 'Field cannot be empty'
validator(' '); // 'Field cannot be empty'
validator('hello'); // null
You can also chain validators like this:
final validator = Validators.Required(
next: Validators.Email(),
);
validator(''); // 'Field cannot be empty'
validator(' '); // 'Field cannot be empty'
validator('hello'); // 'Invalid email'
Implementation
static String? Function(String? value)? Required({
String errorMessage = 'Field cannot be empty',
String? Function(String value)? next,
}) {
return (value) {
if (value == null || value.trim().isEmpty) {
return errorMessage;
}
if (next != null) {
return next(value);
}
return null;
};
}