How to validate if the value of one form is equal to the value of the other in the Textformfield attribute'Validator()

Asked

Viewed 28 times

0

Hello!

I have a _textFieldValue() component, so you don’t have to replay the same code more than once.

  1. Component _textFieldValue()
Widget _textFieldValue(String title, TextEditingController controller) {
  return TextFormField(
    validator: (value){
      if(value.isEmpty) return 'Campo obrigatório';
      if(int.parse(value) < 0) return 'Informe um valor igual ou maior que 0.';
      return null;
    },
    keyboardType: TextInputType.number,
    controller: controller,
    decoration: InputDecoration(
      filled: true,
      fillColor: Colors.blue.shade100,
      border: OutlineInputBorder(),
      labelText: title,
      labelStyle: TextStyle(fontSize: 20),
    ),
  );
}
  1. Applying the _textFieldValue()

inserir a descrição da imagem aqui

  1. View

inserir a descrição da imagem aqui

As you can see, I’m validating the form. And my question is, how can I validate if the value entered in the first field ('Minimum') is equal to the value entered in the second field ('Maximum'').

You can do it?

  • You want this validation to be done from within the method you put invalidator? That is, do you want to receive the value of one textfield inside the other? Or this validation can be done outside?

  • Hello. Naslausky. It would be nice if it were within the method, but if it were not possible it could be outside.

  • If you go inside, the same validation error will happen twice, once in each field. It’s not very elegant, but if this is what you want, you can pass two controllers as a parameter to your widget (instead of one) and compare the values with controller.value == outroController.value. If that’s what you want I’ll write a reply later.

  • 1

    Thanks for the help! It worked perfectly. It only took a few things to change. I took the textFormField from a component and put it right into the 'main code'. And to do the validation once pass the controller.value, I directly put _controllerMin.text == _controllerMax.text.

1 answer

0

Just check the controller values:

validator: (text) {
   if(text == outroController.value) {
     return null;
   } else {
     return 'não combinam';
   }
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.