LoginSignup
3
2

More than 3 years have passed since last update.

【Flutter, Dart】Validationを実装する

Last updated at Posted at 2020-06-30

バリデーション

validation_helper.dart
// 英数のみ、6桁のバリデーション

class Validator {
  Validator._();

  static bool isValidHoge(String hoge) {
    const _hogeRegExpString = r'^[0-9a-zA-Z]{6}$';
    return RegExp(_hogeRegExpString, caseSensitive: true).hasMatch(hoge);
  }
}

接頭辞rを付することでraw(生)文字列として扱うことができます。(エスケープシーケンス回避のため)

参考記事
1. form用正規表現判定/備忘
2. RegExp constructor

実装例

example_notifier.dart
// freezedを使用した実装例

class Hoge {
  void onChangeHoge(String hoge) {
    state = state.copyWith(hoge: hoge);
    if (Validator.isValidHoge(hoge)) {
      state = state.copyWith(isEnable: true);
    } else {
      state = state.copyWith(isEnable: false);
    }
  }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2