Flutter: Setting a range of accepted values and multiple conditions to a TextFormField validator

6,221

If you parse the value to a number, then you don't need to use regexp

var numValue = int.tryParse(value);
if(numValue >= 5 && numValue < 100) {
  return true;
} 

You can for example check if value.length > 0 and numValue > 0 to know that the string was not a valid number for

"Age cannot contain characters other than numbers."
Share:
6,221
Maria Morejon
Author by

Maria Morejon

Updated on December 05, 2022

Comments

  • Maria Morejon
    Maria Morejon over 1 year

    I'm using many TextFormFields as number input fields and want to ensure the user can only enter a value from an acceptable range of numbers. For example an age field should only accept numbers between 18 and 100, and only integers rather than decimals.

    Which brings me to the second half of my question: how can I use the validator property to specify two or more conditions to one field? Say for the age field; input must be inside designated range, input must be a whole number, input must not be empty. I am able to create a working validator with, say, one of these conditions, but how do I ask it to validate multiple things in the same TextFormField?

    Please let me know if there is any other information I can provide to assist you in answering, I didn't feel a code example would have been useful because the issue is non-specific.

    EDIT: have (for the most part) figured out the multiple conditions issue, still in the dark about creating a number range of accepted values. A specific example solution for my age field would be a big help. Example code:

    ...
    String validateAge(String value){
     String pattern = r'(^[0-9]*$)';
     RegExp regExp = new RegExp(pattern);
     if (value.length == 0){
      return "Age is required.";
     } else if (!regExp.hasMatch(value)){
      return "Age cannot contain characters other than numbers.";
     }
    }
    ...
    new TextFormField(
     decoration: InputDecoration(
      hintText: "Age"
     ),
     validator: validateAge,
     autoValidate: true,
    ),
    
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    Glad to hear :)