【问题标题】:How to check entered phone number is valid or not with flutter?如何检查输入的电话号码是否有效?
【发布时间】:2019-12-20 14:58:47
【问题描述】:

我正在尝试检查输入的电话号码是否有效。 意思是,如果我输入错误的数字,世界上不存在,所以它会向我显示内容为“请输入有效数字”的敬酒

 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);
    },
   ),
 )

【问题讨论】:

  • 你试过TextFieldForm吗?
  • 是的,但我不需要验证器,因为我已经验证了 .只是想检查输入的电话号码是否存在?
  • @ShrutiRamnandanSharma 为此,您需要拨打该号码
  • 我想你应该解释一下什么是“有效号码”?在前端,我们使用正则表达式作为 Samcom 的答案。在后端,我们不知道是否存在什么号码,但调用api,或者如果你是ISP,你可以知道它是否存在于世界上。
  • @ShrutiRamnandanSharma 找到任何解决方案了吗?

标签: flutter dart


【解决方案1】:

请查看此文档https://medium.com/@nitishk72/form-validation-in-flutter-d762fbc9212c

代码 sn -p TextFormField 验证器

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;
  }

验证电话号码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;
}    

带包https://pub.dev/packages/flutter_form_builder 支持内置和自定义验证器

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";
    },
],
),

您可以将自己的电话号码验证逻辑放入验证器中

【讨论】:

    【解决方案2】:
    - 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;
    }         
    

    【讨论】:

    • 谢谢,但此解决方案无法解决我的问题。能否请您重新阅读我的帖子?
    【解决方案3】:

    我认为, 解决方案在我的代码中 我太笨了,认不出来了。

    请看代码中的cmets。

    
        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
          );
        } 
      }
    

    【讨论】:

      【解决方案4】:

      使用this 进行基于国家/地区的电话号码格式检查。

      【讨论】:

      • 撰写本文时不支持 Dart
      猜你喜欢
      • 1970-01-01
      • 2022-06-21
      • 2013-06-08
      • 2017-10-27
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      相关资源
      最近更新 更多