cake_wallet/lib/core/validator.dart

60 lines
1.6 KiB
Dart
Raw Normal View History

2020-06-20 07:10:00 +00:00
abstract class Validator<T> {
Validator({required this.errorMessage, this.useAdditionalValidation});
2020-06-20 07:10:00 +00:00
final String errorMessage;
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
String? call(T? value) => !isValid(value) ? errorMessage : null;
2020-06-20 07:10:00 +00:00
}
class TextValidator extends Validator<String> {
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;
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) {
return isAutovalidate ? true : false;
2020-06-20 07:10: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
}
bool match(String value) =>
pattern != null ? RegExp(pattern!).hasMatch(value) : false;
2020-06-20 07:10:00 +00:00
}