gpt4 book ai didi

regex - inputFormatter 应该只允许十进制数和负数

转载 作者:行者123 更新时间:2023-12-03 02:41:16 24 4
gpt4 key购买 nike

我想让用户只添加数字“12345”和十进制数字(如“21321.12312”)和负数(如 -23423.32432)。用户不应能够添加多个“.”。像“12..32”并在输入的第一个添加“-”,像-324.34而不是324-4323。
我使用了这个正则表达式 r'^(-?\d+\.\d+)(\s*,\s*-?\d+\.\d+)+$'但不能输入任何东西。
文本字段代码:

TextFormField(
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'^(-?\d+\.\d+)(\s*,\s*-?\d+\.\d+)+$')),
],
controller: budget,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding:
EdgeInsets.only(right: 20, left: 20, top: 10, bottom: 10),
hintText: getTranslated(context, "budget_example"),
hintStyle: TextStyle(fontSize: 13, fontFamily: "tahoma"),
border: OutlineInputBorder(
borderSide: BorderSide(width: 1, color: MyColors.secondary),
borderRadius: BorderRadius.circular(100),
),
),
),

最佳答案

只允许 1 。
允许否定
在开头放置负号
我们应该创建自己的输入格式化程序

import 'package:flutter/services.dart';

class NumberTextInputFormatter extends TextInputFormatter {
NumberTextInputFormatter({this.decimalRange}) : assert(decimalRange == null || decimalRange > 0);

final int decimalRange;

@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
TextEditingValue _newValue = this.sanitize(newValue);
String text = _newValue.text;

if (decimalRange == null) {
return _newValue;
}

if (text == '.') {
return TextEditingValue(
text: '0.',
selection: _newValue.selection.copyWith(baseOffset: 2, extentOffset: 2),
composing: TextRange.empty,
);
}

return this.isValid(text) ? _newValue : oldValue;
}

bool isValid(String text) {
int dots = '.'.allMatches(text).length;

if (dots == 0) {
return true;
}

if (dots > 1) {
return false;
}

return text.substring(text.indexOf('.') + 1).length <= decimalRange;
}

TextEditingValue sanitize(TextEditingValue value) {
if (false == value.text.contains('-')) {
return value;
}

String text = '-' + value.text.replaceAll('-', '');

return TextEditingValue(text: text, selection: value.selection, composing: TextRange.empty);
}
}
和(不要忘记导入之前的类)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class NumberFormField extends StatelessWidget {
final InputDecoration decoration;
final TextEditingController controller;
final int decimalRange;

const NumberFormField({Key key, this.decoration, this.controller, this.decimalRange}) :super(key: key);

@override
Widget build(BuildContext context) {
return TextFormField(
decoration: this.decoration,
controller: this.controller,
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
WhitelistingTextInputFormatter(RegExp(r'[\d+\-\.]')),
NumberTextInputFormatter(decimalRange: this.decimalRange),
],
);
}
}

关于regex - inputFormatter 应该只允许十进制数和负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64117471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com