cake_wallet/lib/core/validator.dart

43 lines
1.1 KiB
Dart
Raw Normal View History

2020-06-20 07:10:00 +00:00
import 'package:flutter/foundation.dart';
abstract class Validator<T> {
2022-10-12 17:09:57 +00:00
Validator({required this.errorMessage});
2020-06-20 07:10:00 +00:00
final String errorMessage;
2022-10-12 17:09:57 +00:00
bool isValid(T? value);
2020-06-20 07:10:00 +00:00
2022-10-12 17:09:57 +00:00
String? call(T? value) => !isValid(value) ? errorMessage : null;
2020-06-20 07:10:00 +00:00
}
class TextValidator extends Validator<String> {
TextValidator(
2020-07-06 20:09:03 +00:00
{this.minLength,
this.maxLength,
this.pattern,
2022-10-12 17:09:57 +00:00
String errorMessage = '',
2020-07-06 20:09:03 +00:00
this.length,
2022-10-12 17:09:57 +00:00
this.isAutovalidate = false})
2020-06-20 07:10:00 +00:00
: super(errorMessage: errorMessage);
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
}
2020-07-06 20:09:03 +00:00
return value.length > (minLength ?? 0) &&
(length?.contains(value.length) ?? true) &&
2022-10-12 17:09:57 +00:00
((maxLength ?? 0) > 0 ? (value.length <= maxLength!) : true) &&
2020-06-20 07:10:00 +00:00
(pattern != null ? match(value) : true);
}
2022-10-12 17:09:57 +00:00
bool match(String value) => pattern != null ? RegExp(pattern!).hasMatch(value) : false;
2020-06-20 07:10:00 +00:00
}