2020-06-20 07:10:00 +00:00
|
|
|
abstract class Validator<T> {
|
2023-05-15 12:39:00 +00:00
|
|
|
Validator({required this.errorMessage, this.useAdditionalValidation});
|
2020-06-20 07:10:00 +00:00
|
|
|
|
|
|
|
final String errorMessage;
|
2023-05-15 12:39:00 +00:00
|
|
|
final bool Function(T)? useAdditionalValidation;
|
2020-06-20 07:10:00 +00:00
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
bool isValid(T? value);
|
2020-06-20 07:10:00 +00:00
|
|
|
|
2023-05-15 12:39:00 +00:00
|
|
|
String? call(T? value) => !isValid(value) ? errorMessage : null;
|
2020-06-20 07:10:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
class TextValidator extends Validator<String> {
|
2023-05-15 12:39:00 +00:00
|
|
|
TextValidator({
|
|
|
|
bool Function(String)? useAdditionalValidation,
|
|
|
|
this.minLength,
|
|
|
|
this.maxLength,
|
|
|
|
this.pattern,
|
|
|
|
String errorMessage = '',
|
|
|
|
this.length,
|
|
|
|
this.isAutovalidate = false,
|
|
|
|
}) : super(
|
|
|
|
errorMessage: errorMessage,
|
|
|
|
useAdditionalValidation: useAdditionalValidation);
|
2020-06-20 07:10:00 +00:00
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
final int? minLength;
|
|
|
|
final int? maxLength;
|
|
|
|
final List<int>? length;
|
2020-07-31 15:29:21 +00:00
|
|
|
final bool isAutovalidate;
|
2022-10-12 17:09:57 +00:00
|
|
|
String? pattern;
|
2020-06-20 07:10:00 +00:00
|
|
|
|
|
|
|
@override
|
2022-10-12 17:09:57 +00:00
|
|
|
bool isValid(String? value) {
|
2020-06-20 07:10:00 +00:00
|
|
|
if (value == null || value.isEmpty) {
|
2020-07-31 15:29:21 +00:00
|
|
|
return isAutovalidate ? true : false;
|
2020-06-20 07:10:00 +00:00
|
|
|
}
|
|
|
|
|
2023-05-15 12:39:00 +00:00
|
|
|
final greaterThanMinLength = value.length > (minLength ?? 0);
|
|
|
|
if (!greaterThanMinLength) return false;
|
|
|
|
|
|
|
|
final lengthMatched = length?.contains(value.length) ?? true;
|
|
|
|
if (!lengthMatched) return false;
|
|
|
|
|
|
|
|
final lowerThanMaxLength =
|
|
|
|
(maxLength ?? 0) > 0 ? (value.length <= maxLength!) : true;
|
|
|
|
if (!lowerThanMaxLength) return false;
|
|
|
|
|
|
|
|
if (pattern == null) return true;
|
|
|
|
|
|
|
|
final valueMatched = match(value);
|
|
|
|
final valueValidated = useAdditionalValidation != null
|
|
|
|
? useAdditionalValidation!(value) || valueMatched
|
|
|
|
: valueMatched;
|
|
|
|
|
|
|
|
return valueValidated;
|
2020-06-20 07:10:00 +00:00
|
|
|
}
|
|
|
|
|
2023-05-15 12:39:00 +00:00
|
|
|
bool match(String value) =>
|
|
|
|
pattern != null ? RegExp(pattern!).hasMatch(value) : false;
|
2020-06-20 07:10:00 +00:00
|
|
|
}
|