TextInputFormatter篇
1.忽略特殊字符
import 'package:flutter/services.dart';
class IgnoreOtherFormatter extends TextInputFormatter{
var _regExp=r"^[\u4E00-\u9FA5A-Za-z0-9_]+$";
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length>0){
if(RegExp(_regExp).firstMatch(newValue.text)!=null){
return newValue;
}
return oldValue;
}
return newValue;
}
}
2.只能輸入數字和小寫字母
import 'package:flutter/services.dart';
class OnlyInputNumberAndLowWorkFormatter extends TextInputFormatter{
var _regExp=r"^[a-z0-9_]+$";
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length>0){
if(RegExp(_regExp).firstMatch(newValue.text)!=null){
return newValue;
}
return oldValue;
}
return newValue;
}
}
3.只能輸入數字和字母
import 'package:flutter/services.dart';
class OnlyInputNumberAndWorkFormatter extends TextInputFormatter{
var _regExp=r"^[A-Za-z0-9_]+$";
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length>0){
if(RegExp(_regExp).firstMatch(newValue.text)!=null){
return newValue;
}
return oldValue;
}
return newValue;
}
}
4.忽略表情
RegExp regexp=RegExp("[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
inputFormatters.add(BlacklistingTextInputFormatter(regexp));
4.只能輸入數字
WhitelistingTextInputFormatter.digitsOnly
5.長度限制(限制6位)
LengthLimitingTextInputFormatter(6)
6.限制單行
BlacklistingTextInputFormatter.singleLineFormatter
7.輸入價錢
FilteringTextInputFormatter.allow(RegExp(r'^\d+(\.)?(\d+)?'))
8.輸入最多兩位小數的價錢
FilteringTextInputFormatter.allow(RegExp(r'^\d+(\.)?[0-9]{0,2}'))
正則校驗篇
///手機號驗證
static bool isChinaPhoneLegal(String str) {
return RegExp(
r"^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$")
.hasMatch(str);
}
///郵箱驗證
static bool isEmail(String str) {
return RegExp(
r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")
.hasMatch(str);
}
///驗證URL
static bool isUrl(String value) {
return RegExp(
r"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+")
.hasMatch(value);
}
///驗證身份證
static bool isIdCard(String value) {
return RegExp(
r"\d{17}[\d|x]|\d{15}")
.hasMatch(value);
}
///驗證中文
static bool isChinese(String value) {
return RegExp(
r"[\u4e00-\u9fa5]")
.hasMatch(value);
}
// 驗證是否為純字母
static bool isLetter(String str) {
final reg = RegExp(r"^[ZA-ZZa-z_]+$");
return reg.hasMatch(str);
}
// 驗證是否為數字
static bool isNumber(String str) {
final reg = RegExp(r"^[0-9_]+$");
return reg.hasMatch(str);
}
//驗證是否包含特殊字符
static bool isHaveSpecialCharacters(String input) {
final reg = new RegExp(r'[`~!@#$%^&*()_+=|;:(){}'',\\[\\].<>/?~匾乓!@#¥%……&*()——+|{}【】‘昔案;:”“’。根时,示括、?-]');
return reg.hasMatch(input);
}