React本机表单验证

k5hmc34c  于 2022-11-17  发布在  React
关注(0)|答案(3)|浏览(202)

我使用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+)*(\.\w{2,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>

);
  }
}
7eumitmz

7eumitmz1#

我推荐使用formikyup来轻松构建一个带有输入验证的登录表单。这两个包集成在一起时,由于它们的两个特性,简化了代码库。
请看一下这里的CodeSandbox片段https://codesandbox.io/s/stack-overflow-54204827-llvkzc?file=/index.tsx:254-656。注意,我在这里使用的是typescript
package.json文件在编写代码段时为:

"dependencies": {
    ...
    "formik": "2.2.9",
    ...
    "yup": "0.32.11"
  },

为了分解解决方案,首先我们为Login表单定义yup模式:
请注意,您可以稍后调整正则表达式模式,因为此密码验证接受最少6到最多12个字符,其中至少包含一个大写字母、一个小写字母、一个数字和一个特殊字符

/**
 * The `yup` Login Form schema
 */
const LoginSchemaA = Yup.object().shape({
  email: Yup.string()
    .email("Invalid email.")
    .required("Email must be provided."),
  password: Yup.string()
    .required("Password must be provided.")
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{6,12})/,
      "Password must be minimum 6 and maximum 12 characters."
    )
});

注意,这里的.email("Invalid email.")是默认使用的电子邮件验证功能。您可以删除它,并使用.matches(...)函数代替您自己的正则表达式。
还有<Formik />部分供您进一步用途:

<Formik
        initialValues={{
          email: "",
          password: ""
        }}
        validationSchema={LoginSchemaA}
        onSubmit={(
          values: Values,
          { setSubmitting }: FormikHelpers<Values>
        ) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 500);
        }}
      >
        {({ errors, touched }) => (
          <Form>
            <label htmlFor="email">Email</label>
            <Field
              id="email"
              name="email"
              placeholder="john.doe@email.com"
              type="email"
            />
            {errors.email && touched.email ? (
              <div style={{ color: "red" }}>{errors.email}</div>
            ) : null}

            <label htmlFor="password">Password</label>
            <Field id="password" name="password" type="password" />
            {errors.password && touched.password ? (
              <div style={{ color: "red" }}>{errors.password}</div>
            ) : null}

            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>

最后,您可能希望获取values本身以供进一步使用-忽略setTimeoutalertsetSubmitting用法。
JSON.stringify(values, null, 2)的输出示例如下:

{
  "email": "john.doe@test.com",
  "password": "Awesome@Password!2022"
}

希望这对您的react-native编码之旅有所帮助!

ygya80vv

ygya80vv2#

[电子邮件,设置电子邮件] =使用状态('');密码,设置密码] =使用状态('');
变量有效正则表达式= /^[a-zA-Z 0 -9.!#$%&'*+/=?^_'{|(2)(1)(2)(1)(2)(1)(2)(1)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2))(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)(2)if(!email){Toast.show(“电子邮件是必需的。”);如果您的电子邮件是无效的,请点击这里返回。} else if(!password){ Toast.show('需要密码。');}

k97glaaz

k97glaaz3#

这是我代码,你可以试试

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>
    )
  }
}
<!-- begin snippet: js hide: false console: true babel: false -->
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

相关问题