flutter 如何在一个文本表单域中使用两个变量验证器?

5us2dqdw  于 2023-01-31  发布在  Flutter
关注(0)|答案(1)|浏览(162)

我想问一下是否有任何关于如何在条件语句中比较这两个变量的方法。正如你所看到的,couponSalePriceCtrlrcouponOrigPriceCtrlr。我想验证用户在sale price中的输入不应该大于original price,但似乎validator只接受(value)参数和String数据类型。

Widget editCouponSalePriceWidget(couponSalePriceCtrlr, couponOrigPriceCtrlr) {
  // converted the variable parameters into double data type
  double convertedSalePrice = double.parse(couponSalePriceCtrlr);
  double convertedOrigPrice = double.parse(couponOrigPriceCtrlr);
  return Padding(
    padding: const EdgeInsets.symmetric(horizontal: 0.0),
    child: TextFormField(
      style: const TextStyle(fontFamily: 'Poppins', fontSize: 13),
      controller: couponSalePriceCtrlr,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        suffixText: "*",
        suffixStyle: TextStyle(color: Colors.red),
        labelText: 'Sale Price',
        labelStyle: const TextStyle(
            fontSize: 15, fontFamily: 'Poppins', color: Color(0xFF152C4C)),
        isDense: true,
        prefixIcon: const Icon(Icons.person),
        enabledBorder: OutlineInputBorder(
          borderSide: const BorderSide(color: Color(0xFFCECECE)),
          borderRadius: BorderRadius.circular(12),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFFCECECE)),
        ),
        hintText: 'Orig Price',
        fillColor: const Color(0xFFFEFEFE),
        filled: true,
      ),
     // however the validator only accepts, a string data type.
      validator: (convertedSalePrice,convertedOrigPrice) {
        if (convertedSalePrice!.isEmpty ||
            !RegExp(r'[0-9]+[,.]{0,1}[0-9]*').hasMatch(convertedSalePrice)) {
          return "Please enter a valid original price.";
        } else {
          return null;
        }
      },
    ),
  );
}
6mw9ycah

6mw9ycah1#

我假设你有两个TextFormField,一个是原价,一个是特价,当然是String类型,这是规则:)所以你需要把它转换成整型/双精度型,如果你的keyboardType是数字,就不需要检查用户输入的是字符串类型,否则就检查。

TextFormField(
  controller: couponOrigPriceCtrlr,
  keyboardType: TextInputType.number,
)
TextFormField(
  controller: convertedSalePrice,
  keyboardType: TextInputType.number,
  validator: (saleStr) {
    double originalDouble = double.parse(couponOrigPriceCtrlr.text);
    double saleDouble = double.parse(saleStr.text);
    // check what ever you want here
    // ...

  }
)

相关问题