/*
 * @Author: XianKaiQun
 * @Date: 2020-09-07 15:10:33
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-05-26 14:55:20
 * @Description: 
 */

///多项验证器
///```dart
///WMultiFormValidatorUtil([
/// WValidatorUtil(),
/// WValidatorUtil(),
/// WValidatorUtil(),
/// ...
///]).validator(value);
///
///```
class WMultiValidatorUtil {
  final List<WValidatorUtil> validators;

  WMultiValidatorUtil(this.validators);

  String? validate(String value) {
    String? errorText;
    for (var item in validators) {
      errorText = item.validate(value);
      if (errorText != null) {
        break;
      }
    }
    return errorText;
  }
}

///单项验证器
///```dart
/// WValidatorUtil().validator(value)
///```
class WValidatorUtil {
  final String? Function(dynamic value) validate;
  WValidatorUtil(String? Function(dynamic value) validator)
      : validate = validator;

  ///验证手机号
  static WValidatorUtil isPhoneNumber([String errorText = '请输入正确手机号']) {
    return WValidatorUtil((dynamic value) {
      final regExp = RegExp(r"1[3456789]\d{9}$");
      final boolean = regExp.hasMatch(value ?? '');
      return boolean ? null : errorText;
    });
  }

  ///验证必须存在
  static WValidatorUtil isRequired([String errorText = '此项不可为空']) {
    return WValidatorUtil((dynamic value) {
      final list = [null, [], ''];
      final has = list.indexOf(value) != -1;
      return has ? errorText : null;
    });
  }

  ///验证最大范围
  static WValidatorUtil isOutOfRange(
      [String errorText = '此项超出范围', int? maxSize]) {
    return WValidatorUtil((dynamic value) {
      final boolean = value < maxSize;
      return boolean ? null : errorText;
    });
  }
}
