-1

I have a form for user information and if one of the fields are empty I want to disable the submit button but my setState is not updating the flags. Here is my validateFields function which is being called inside a build method. Regex is 100% correct (I checked it multiple times)

void validateFields() {
    RegExp regExp = new RegExp(r'[!@#<>?"\s:_`~;[\]\\|=+)(*&^%-]|^$');
    if (regExp.hasMatch(nameController.text) || regExp.hasMatch(surnameController.text) || regExp.hasMatch(phoneController.text)){
      setState(() {
        isButtonDisabled = true;
      });
    }
    else {
      setState(() {
        isButtonDisabled = false;
      });
    }
  }

And Here is my submit button

onPressed: isButtonDisabled ? null : (){
 //upload the form
}
ulmas
  • 517
  • 1
  • 5
  • 15

2 Answers2

0

setState method rebuilds the widget tree, so all your widgets will get refreshed.

One way is to consider checking for regex validation after the button is clicked. Simply show a snackbar warning if regex doesnt match or do the next action if it matches.

Second would be to change the state of button when some text is submitted in the text field. You can use TextController to change the state of the button whenever something is written.

Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33
0

I resolved the problem by adding the listener to the textController

nameController.addListener(() { 
     validateField(nameController.text);
    });
  void validateField(text) {
    RegExp regExp = new RegExp(r'[!@#<>?"\s:_`~;[\]\\|=+)(*&^%-]|^$');
   if (regExp.hasMatch(text)) {
       setState(() {
         isButtonDisabled = true;
       });
     } else {
       setState(() {
         isButtonDisabled = false;
       });
     }
  }
}
ulmas
  • 517
  • 1
  • 5
  • 15