Skip to content

Instantly share code, notes, and snippets.

@Jojoooo1
Last active September 17, 2020 21:30
Show Gist options
  • Save Jojoooo1/61dae966645ee83127ed92e295585a4e to your computer and use it in GitHub Desktop.
Save Jojoooo1/61dae966645ee83127ed92e295585a4e to your computer and use it in GitHub Desktop.
Input validation flutter
// Simplified version with focusOut validation
Obx(
() => Focus(
onFocusChange: (hasFocus) {
if (!hasFocus) {
controller.stateTaxIdController.refresh();
GetUtils.isCnpj(stateTaxIdMask.getUnmaskedText());
}
},
child: TextFormFieldOnPrimary(
controller: controller.stateTaxIdController.value,
keyboardType: TextInputType.number,
mask: [stateTaxIdMask],
hintText: '87.880.524/0001-00',
//
// onChanged: (value) => controller.verifyCnpjIsValid(stateTaxIdMask.getUnmaskedText()),
errorText: GetUtils.isCnpj(stateTaxIdMask.getUnmaskedText()) || controller.stateTaxIdController.value.text.length == 0
? null
: AppText.stateTaxIdInvalid,
validator: (value) {
if (GetUtils.isCnpj(value)) return null;
return 'CNPJ inválido';
},
),
),
)
// TextFormField
Obx(
() => TextFormFieldOnPrimary(
controller: controller.stateTaxIdController,
keyboardType: TextInputType.number,
mask: [stateTaxIdMask],
hintText: '87.880.524/0001-00',
//
onChanged: (value) => controller.verifyCnpj(stateTaxIdMask.getUnmaskedText()),
errorText: controller.isCnpjValid.value ? null : AppText.cnpjInvalid,
validator: (value) {
if (GetUtils.isCnpj(value)) {
return null;
}
return 'CNPJ inválido';
},
)
)
// Submit button
ButtonBase(
text: "próximo",
onPressed: () {
if (_formKey.currentState.validate()) {
controller.pageController.nextPage(duration: Duration(milliseconds: 200), curve: Curves.fastOutSlowIn);
} else {
ShowSnackBar.error("Corrigir os campos em destaque");
}
},
icon: Icons.arrow_forward,
)
// Controller
class SignupOperatorController extends GetxController {
final CompanyRepository companyRepository;
SignupOperatorController({@required this.companyRepository}) : assert(companyRepository != null);
static SignupOperatorController get to => Get.find();
// Controllers
final TextEditingController stateTaxIdController = TextEditingController();
// Getters
String get stateTaxId => stateTaxIdController.text;
// Verications
final isCnpjValid = true.obs; // start valid
verifyCnpj(String value) {
stateTaxId == "" ? isCnpjValid.value = true : isCnpjValid.value = GetUtils.isCnpj(value);
}
@override
void onInit() async {
print("[SignupOperatorController] - onInit");
pageController = new PageController();
}
@override
Future<void> onClose() async {
print("[SignupOperatorController] - onClose");
clear();
stateTaxIdController?.dispose();
super.onClose();
}
void clear() {
stateTaxIdController.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment