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