React Native 表单验证

Posted

技术标签:

【中文标题】React Native 表单验证【英文标题】:React Native Form Validation 【发布时间】:2019-01-15 18:26:27 【问题描述】:

我使用 react-native 创建了一个登录表单,我想验证每个字段,但我不知道该怎么做。我对 react-native 很陌生,所以我想向任何人寻求帮助。表单验证应在以下情况下显示错误:

输入表单为空 电子邮件文本不是电子邮件形式。 密码文本不满足上述条件。 如果输入表单有错误,则应禁用登录按钮。 如果输入表单没有任何错误,显示警报以通知登录 成功

示例图片验证:

这是我的代码:

import React from 'react';
import  StyleSheet, Text, View, Image, TextInput, Dimensions, ScrollView, 
CheckBox, TouchableOpacity  from 'react-native';
import logo from './image/Logo.png'

const  width: WIDTH  = Dimensions.get('window')

export default class App extends React.Component 
  constructor()
    super();
    this.state=
      check:false,
      email: '',
    ;
    this.validates = this.validates.bind(this);
  

  CheckBoxText()
      this.setState(
        check:!this.state.check,
      )
  


  validates = () =>  

    let text = this.state.email; 
    let emailError = this.state.emails;
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w2,3)+$/ ; 
    if(reg.test(text) === false) 
     
    console.warn("Invalid email")
    this.setState(email:text) 
    return false; 
     
    else  
    this.setState(email:text) 
    console.log("Email is Correct"); 
     
 

  render() 
    return (

  <View>
    <View style=styles.container>
      <Image source=logo style=styles.logo/>
    </View>

    <View style = styles.container2>
      <Text style=styles.emailAdd>
        Email
      </Text>
      <TextInput 
            onChangeText=(text) => this.setState(email:text) 
            type='email'
            value=this.state.email 
            keyboardType='email-address'
            style=styles.emailInput
            placeholder='Input Email Address'
            underlineColorandroid='transparent'/>

    </View>

    <View style = styles.container3>
      <Text style=styles.password>
        Password
      </Text>
      <TextInput 
            style=styles.passwordInput
            placeholder='Input Password'
            secureTextEntry=true
            underlineColorAndroid='transparent'/>

    </View>

    <View style = styles.container4>

          <View>
            <CheckBox value=this.state.check onChange=()=>this.CheckBoxText() style=styles.rememberMe/>
          </View>
          <View>
            <Text style=styles.remember>Remember me</Text>
          </View>
    </View>

    <TouchableOpacity style=styles.btnLogin onPress=this.validates >
          <Text style=styles.txtLogin>Sign In</Text>
    </TouchableOpacity>


  </View>

);
  

【问题讨论】:

【参考方案1】:

这是我的代码,你可以试试这个

import React,  Component  from "react"
import  View, Button  from "react-native"

import TextField from "textfield"
import validation from "validation"
import validate from "validation_wrapper"

export default class Form extends Component 
  constructor(props) 
    super(props)

    this.state = 
      email: "",
      emailError: "",
      password: "",
      passwordError: ""
    
  

  register() 
    const emailError = validate("email", this.state.email)
    const passwordError = validate("password", this.state.password)

    this.setState(
      emailError: emailError,
      passwordError: passwordError
    )

    if (!emailError && !passwordError) 
      alert("Details are valid!")
    
  

  render() 
    return (
      <View>
        <TextField
          onChangeText=(value) => this.setState( email: value.trim() )
          onBlur=() => 
            this.setState(
              emailError: validate("email", this.state.email)
            )
          
          error=this.state.emailError
        />

        <TextField
          onChangeText=(value) => this.setState( password: value.trim() )
          onBlur=() => 
            this.setState(
              passwordError: validate("password", this.state.password)
            )
          
          error=this.state.passwordError
          secureTextEntry=true
        />

        <Button title="Register" onPress=this.validateRegister />
      </View>
    )
  

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

const validation = 
  email: 
    presence: 
      message: "^Please enter an email address"
    ,
    email: 
      message: "^Please enter a valid email address"
    
  ,

  password: 
    presence: 
      message: "^Please enter a password"
    ,
    length: 
      minimum: 5,
      message: "^Your password must be at least 5 characters"
    
  


export default validation

import validation from "validation.js"

export default function validate(fieldName, value) 
  // Validate.js validates your values as an object
  // e.g. var form = email: 'email@example.com'
  // Line 8-9 creates an object based on the field name and field value
  var formValues = 
  formValues[fieldName] = value

  // Line 13-14 creates an temporary form with the validation fields
  // e.g. var formFields = 
  //                        email: 
  //                         presence: 
  //                          message: 'Email is blank'
  //                         
  //                       
  var formFields = 
  formFields[fieldName] = validation[field]

  // The formValues and validated against the formFields
  // the variable result hold the error messages of the field
  const result = validatejs(formValues, formFields)

  // If there is an error message, return it!
  if (result) 
    // Return only the field error message if there are multiple
    return result[field][0]
  

  return null
import React from "react"
import  View, TextInput, Text  from "react-native"

const TextField = (props) => (
  <View>
    <TextInput />
    props.error ? <Text>props.error</Text> : null
  </View>
)

export default TextField

【讨论】:

以上是关于React Native 表单验证的主要内容,如果未能解决你的问题,请参考以下文章

React Native - 如何正确验证文本输入?

React Native AsyncStorage getItem 返回承诺而不是值

在 React Native 上使用身份验证器 UI 自定义 AWS 放大

在 React Native 上通过 Auth0 进行 Instagram 身份验证(不是登录)?

React Native:在开玩笑的单元测试中更新上下文 api 值

[ React+ant Design] ProFrom高级表单 - 基本的几种格式验证