Home > OS >  Flutter Validate either email text field or phoneField
Flutter Validate either email text field or phoneField

Time:03-17

I have an email textfield and a phone textfield inside my application. My objective is to validate these by following the condition. if i have value inside email textfield i dont have to validate phone textfield. similarly if phone field has value i dont have to validate email.

I have wrote validate functions as follows

   _validateEmail(String userEmail) {
    if (!isValidEmail(userEmail)) {
      ErrorSnackbar(title: 'Error', message: 'invalidEmail');
      return false;
    } else {
      return true;
    }
  }


  validateMobile(String userMobile) {
    String pattern =
        r'^[\ ]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$';
    RegExp regex = RegExp(pattern);
    if (userMobile.isEmpty || !regex.hasMatch(userMobile)) {
      ErrorSnackbar(title: 'Error', message: 'invalidMobile');
      return false;
    } else {
      return true;
    }
  }

Based on the validation i need to complete some api calls

if (validateEmail(emailController.text) || validateMobile(selectedPhoneNumber?.number ?? phoneController.text)) {

// api calls
}

How can i achieve this?

CodePudding user response:

Try this type of logic

if (!isValidEmail(userEmail) && (userMobile.isNotEmpty || regex.hasMatch(userMobile)
) {
      ErrorSnackbar(title: 'Error', message: 'invalidEmail');
      return false;
    }else if (userMobile.isEmpty || !regex.hasMatch(userMobile) && (isValidEmail(userEmail)) {
      ErrorSnackbar(title: 'Error', message: 'invalidMobile');
      return false;
    }
 else {
      return true;
    }

CodePudding user response:

You can try checking for a function before validating.

if(userMobile.isEmpty && userEmail.isNotEmpty)
{
// validation logic
}

if(userMobile.isNotEmpty && userEmail.isEmpty )
{
// validation logic
}
  • Related