Home > OS >  Allow only specific input in TextFormField without validation in Flutter
Allow only specific input in TextFormField without validation in Flutter

Time:11-30

I want to allow the user to only put maximum of 5 numbers between 1 and 10.000, but this TextFormField is not required and should not be submitted through Form validation, but I want to let the user know if he is adding this field, that he can not exceed 10.000 and he must put only numbers from 1 to 10.000. The code for the TextFormField:

TextFormField(
                                keyboardType: TextInputType.number,
                                controller: _number,
                                inputFormatters: <TextInputFormatter>[
                                  FilteringTextInputFormatter.digitsOnly //I have set this so the input is only numbers/digits
                                ],
                                decoration: kTextFieldDecoration.copyWith(
                                  hintText: 'Enter number between 1 and 10.000',
                                  labelText: 'Number from 1 to 10.000',
                                ),
                              ),

I'm not sure how to achieve this, I used regex validation for the rest of the fields, but since this field is not required, I can't validate it through Form validation. Any form of help is appreciated. Thanks in advance!

CodePudding user response:

May try the code below, for your reference https://stackoverflow.com/a/68072967/7972633

Updated version 1

class NumericalRangeFormatter extends TextInputFormatter {
  final double min;
  final double max;

  NumericalRangeFormatter({required this.min, required this.max});

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {

    if (newValue.text == '') {
      return newValue;
    } else if (int.parse(newValue.text) < min) {
      return TextEditingValue().copyWith(text: min.toStringAsFixed(5));
    } else {
      return int.parse(newValue.text) > max ? oldValue : newValue;
    }
  }
}

keyboardType: TextInputType.numberWithOptions(),
inputFormatters: [
   LengthLimitingTextInputFormatter(5) // only allow 5 digit number
],

CodePudding user response:

You can use validator for a field that is not mandatory in this way :

validator: (value) {
    if (value == null || value.isEmpty) {
      return null;
    }else {
      double? num = double.tryParse(value);
      if(num == null)
         return 'Invalid value';
      else if(num < 1 || num > 10)
         return 'Please enter value between 1 and 10.000';
    }
    return null;
},

So, in this way if value is null or empty then we can skip check otherwise perform required check.

CodePudding user response:

Please try this below regex expression

It allows only numbers between 1 to 10,000 and use you may restrict inputs using maxLength property available in TextFormField

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" ?? "",
                    ),
                  ),

  • Related