javascript React Native:手机号码验证只接受数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50441460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:07:06  来源:igfitidea点击:

React Native: mobile number validation accept numeric value only

javascriptreactjsreact-nativereact-native-androidreact-native-ios

提问by Asif vora

How validate mobile number in react native accept the only numeric value.

如何在 react native 中验证手机号码接受唯一的数值。

 <TextInput
      ref='mobileNo'
      keyboardType="numeric"
      style={[styles.textInput, { width: '100%' }]}
      placeholder='Enter mobile number'
      onChangeText={(value) => this.handleChange('mobileNo', value)}   />

I have used keyboardType="numeric"but its accept special character also so I want to accept the only numeric value.

我已经使用过keyboardType="numeric"但它也接受特殊字符,所以我想接受唯一的数值。

采纳答案by Nirmalsinh

You need to check if input string is number or not. Check below code:

您需要检查输入字符串是否为数字。检查以下代码:

 <TextInput
   ref='mobileNo'
   keyboardType="numeric"
   style={[styles.textInput, { width: '100%' }]}
   placeholder='Enter mobile number'
   onChangeText={(value) => 
   let num = value.replace(".", '');
     if(isNaN(num)){
         // Its not a number
     }else{
        this.handleChange('mobileNo', num)}  
     }
 />

回答by Vishal Vaghasiya

Use this validation.

使用此验证。

mobilevalidate(text) {
    const reg = /^[0]?[789]\d{9}$/;
    if (reg.test(text) === false) {
      this.setState({
        mobilevalidate: false,
        telephone: text,
      });
      return false;
    } else {
      this.setState({
        mobilevalidate: true,
        telephone: text,
        message: '',
      });
      return true;
    }
  }

回答by vm909

Try using keyboardType='phone-pad'.

尝试使用keyboardType='phone-pad'.

回答by Anuj Sharma

You can also do this and you don't have to use if or any other statement...

您也可以这样做,而不必使用 if 或任何其他语句...

First of all download this package to your root folder, this is a inbuild package of npmto download type this command in your cmd prompt....

首先将这个包下载到你的根文件夹,这是一个npm的内置包来下载在你的 cmd 提示符下输入这个命令......

npm i react-native-validator-form

Then import it to your project.

然后将其导入到您的项目中。

import { Form, TextValidator } from 'react-native-validator-form';

Then create a class and extend it with React.Componentand copy-paste the following code...

然后创建一个类并使用React.Component扩展它并复制粘贴以下代码...

state = {
    phonenumber: ''
  }

handleSubmit = () => {
   this.refs.form.submit();
}
render() {
    const {phonenumber} = this.state;
    return (
        <Form 
            ref="form"
            onSubmit={this.handleSubmit}
        > 
          <TextValidator
            name="phonenumber"
            validators={['required', 'isNumber','maxNumber:11']}
            errorMessages={['Phonenumber is required', 'Phonenumber invalid' , 'Not a valid number ']}
            placeholder="Phonenumber"
            value={phonenumber}
            onChangeText={(phonenumber) => this.setState({phonenumber})}
        />
           <Button
                title="Submit"
                onPress={this.handleSubmit}
            />
        </Form>
    );
}

回答by Yossi

The way to do this is to check in the onChangeText handler which input was typed and to issue an error if the user entered a non-numeric character.

这样做的方法是在 onChangeText 处理程序中检查输入的内容,并在用户输入非数字字符时发出错误。

If the field is a controlled component (its value is set from a state variable, and the state variable is being set in the onChangeText handler), you can not accept the invalid character at all (so that the user types, for example, a '.', and it is not dven displayed).

如果该字段是受控组件(其值是从状态变量设置的,并且状态变量是在 onChangeText 处理程序中设置的),则您根本不能接受无效字符(因此用户键入,例如'.',并且不显示)。

Whether you explain to the user why his input is not accepted is up to you (either by writing it in the field's label, e.g. "phone number(digits only), or in a string below the field, or by displaying an error).

您是否向用户解释为什么他的输入不被接受取决于您(通过将其写在字段的标签中,例如“电话号码(仅限数字),或在字段下方的字符串中,或​​通过显示错误)。