请尝试以下正则表达式
它只允许 1 到 10,000 之间的数字,并且您可以使用TextFormField 中提供的maxLength属性来限制输入
int validateNumber(String numberVal) {
String patttern = r'^[1-9]([0-9]{0,1})([.][0-9]{1,3})?$';
RegExp regExp = new RegExp(patttern);
if (numberVal.isEmpty || numberVal.length == 0) {
return 1;
} else if (!regExp.hasMatch(numberVal)) {
return 2;
} else {
return 0;
}
}
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
/* autovalidate is disabled */
controller: numController,
keyboardType: TextInputType.numberWithOptions(
decimal: true,
),
maxLength: 6,
onChanged: (val) {},
maxLines: 1,
validator: (value) {
int res = validateNumber(value);
if (res == 1) {
return "Please fill this required field";
} else if (res == 2) {
return "Please enter valid number between 1 to 10.000";
} else {
return null;
}
},
focusNode: numFocus,
autofocus: false,
decoration: InputDecoration(
errorMaxLines: 3,
counterText: "",
filled: true,
fillColor: Colors.white,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
color: Color(0xffE5E5E5),
),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
color: Color(0xffE5E5E5),
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
color: Color(0xffE5E5E5),
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
color: Colors.red,
)),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(
width: 1,
color: Colors.red,
),
),
hintText: "Enter number between 1 to 10.000" ?? "",
),
),