Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check entered phone number is valid or not with flutter?

Tags:

flutter

dart

I'm trying to check to entered phone number is valid or not . means, if I enter the wrong number which does not exist in the world, so it shows me a toast with content "Please enter a valid number"

 Expanded(
   child: TextField(
     keyboardType: TextInputType.phone,
     decoration: InputDecoration(
       border: InputBorder.none, 
       hintText: "Phone Number", 
     ),
     onChanged: (value){
      setState(() {
        phoneValue=value; 
      });
     //String telNo = value==null?("+91" + value) :null;
     print("phoneNumbe:$phoneNo");
     this.phoneNo = isCountryCodeSelected ? "+" + countryCode + value : "+91" + value ;
     print("phoneNo="+phoneNo);
    },
   ),
 )
like image 673
Shruti Ramnandan Sharma Avatar asked Aug 14 '19 04:08

Shruti Ramnandan Sharma


3 Answers

please check this doc https://medium.com/@nitishk72/form-validation-in-flutter-d762fbc9212c

code snippet TextFormField validator

Widget FormUI() {
    return new Column(
      children: <Widget>[
        new TextFormField(
          decoration: const InputDecoration(labelText: 'Name'),
          keyboardType: TextInputType.text,
          validator: validateName,
          onSaved: (String val) {
            _name = val;
          },
        ),
        new TextFormField(
          decoration: const InputDecoration(labelText: 'Mobile'),
          keyboardType: TextInputType.phone,
          validator: validateMobile,
          onSaved: (String val) {
            _mobile = val;
          },
        ),
        new TextFormField(
          decoration: const InputDecoration(labelText: 'Email'),
          keyboardType: TextInputType.emailAddress,
          validator: validateEmail,
          onSaved: (String val) {
            _email = val;
          },
        ),
        new SizedBox(
          height: 10.0,
        ),
        new RaisedButton(
          onPressed: _validateInputs,
          child: new Text('Validate'),
        )
      ],
    );
  }

  String validateName(String value) {
    if (value.length < 3)
      return 'Name must be more than 2 charater';
    else
      return null;
  }

  String validateMobile(String value) {
// Indian Mobile number are of 10 digit only
    if (value.length != 10)
      return 'Mobile Number must be of 10 digit';
    else
      return null;
  }

  String validateEmail(String value) {
    Pattern pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Email';
    else
      return null;
  }

validate phone number Flutter - Validate a phone number using Regex

String validateMobile(String value) {
String patttern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
      return 'Please enter mobile number';
}
else if (!regExp.hasMatch(value)) {
      return 'Please enter valid mobile number';
}
return null;
}    

With package https://pub.dev/packages/flutter_form_builder Support build-in and custom validator

FormBuilderTextField(
            attribute: "age",
            decoration: InputDecoration(labelText: "Age"),
            validators: [
              FormBuilderValidators.numeric(),
              FormBuilderValidators.max(70),
            ],
          ),

FormBuilderTextField(
attribute: "over_18",
decoration: InputDecoration(labelText: "Are you over 18?"),
validators: [
    FormBuilderValidators.required(),
    (val){
        if(val.toLowerCase() != "yes")
            return "The answer must be Yes";
    },
],
),

You can put your own phone number validate logic in validators

like image 99
chunhunghan Avatar answered Nov 23 '22 18:11

chunhunghan


- You could make the first part optional matching either a + or 0 followed by a 9. 
- Then match 10 digits:

- ^(?:[+0]9)?[0-9]{10}$
- ^ Start of string
- (?:[+0]9)? Optionally match a + or 0 followed by 9
- [0-9]{10} Match 10 digits
- $ End of string

//Here is an Example

String validateMobile(String value) {
String patttern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
      return 'Please enter mobile number';
}
else if (!regExp.hasMatch(value)) {
      return 'Please enter valid mobile number';
}
return null;
}         
like image 45
Prashant Samcom Avatar answered Nov 23 '22 17:11

Prashant Samcom


I think, The solution was in my code and I was so dumb ,couldn't recognised it.

please look at the comments in the code.


    final PhoneCodeAutoRetrievalTimeout autoRetrieval=(String verId){
      this.verificationId=verId;
    };

    final PhoneCodeSent smsCodeSent=(String verId, [int forceCodeResend]){
      this.verificationId=verId;    
      smsCodeDialog(context).then((value){        
      }).catchError((onError){
         print(onError);    
      });
    };


//This will verified you number

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) {
     print("verified");
    };

// and if your number doesn't exist or doesn't match with your country code,Then this will show you an error message

    final PhoneVerificationFailed verfifailed=(AuthException exception){
      print("${exception.message}");
       Fluttertoast.showToast(msg: "The number is invalid", backgroundColor: Colors.red); 
       //Fluttertoast.showToast(msg: "${exception.message}"); //
    };

    if(phoneNo !=null){
      await firebaseAuth.verifyPhoneNumber(
        phoneNumber: this.phoneNo,
        codeAutoRetrievalTimeout: autoRetrieval,
        codeSent: smsCodeSent,
        timeout: const Duration(seconds: 10),
        verificationCompleted: verificationCompleted,
        verificationFailed: verfifailed
      );
    } 
  }
like image 26
Shruti Ramnandan Sharma Avatar answered Nov 23 '22 18:11

Shruti Ramnandan Sharma