How to validate in react-native by using formik and yup?

时间:2019-05-22 13:20:21

标签: validation react-native formik yup

How do i show error messages here by using formik and yup? Suppose i want to show an error message for Customer name. How to do this?

    import React, { Component } from 'react';
    import { Text,Alert, TextInput, View, StyleSheet, KeyboardAvoidingView,  ActivityIndicator,  TouchableOpacity, Image, Animated, Easing,} from 'react-native';
    import { Button } from 'react-native-elements'
    import PropTypes from 'prop-types';
    import Dimensions from 'Dimensions';
    import { Router, Scene, Actions } from 'react-native-router-flux';
    import * as Yup from 'yup';
    import { Formik } from 'formik';

    import eyeImg from '../images/eye_black.png';

    const DEVICE_WIDTH = Dimensions.get('window').width;
    const DEVICE_HEIGHT = Dimensions.get('window').height;

I have declared initialValues also. Please help me.

    const initialValues = {
      customer_name: "",
      mobile: "",
      password: "",
      repassword: "",
      email_address: "",
      company_id: "",
      profile_image: "",
      licence_number: "",
      user_status: "Active",
    };

Here are my error messages.

    const customervalidation = Yup.object().shape({
       customer_name: Yup.string().required("Please enter name"),
       email_address: Yup.string()
                     .required("Please enter email address")
                     .email('Please enter a valid email'),
       mobile: Yup.string().required("Please enter mobile"),
       password: Yup.string().required("Please enter password"),
       repassword: Yup.string().oneOf([Yup.ref('password'), null], 'Passwords must match')
    });



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

        this.state = {
          customer_name: '',
          mobile: '',
          password: '',
          cpassword: '',
          email_address: '',
          showPass: true,
          showConfPass: true,

          press: false,
        };

        this.showPass = this.showPass.bind(this);
        this.showConfPass = this.showConfPass.bind(this);
        this._onPress = this._onPress.bind(this);
      }

      showPass() {
        //Alert.alert('Credentials', `${this.state.press}`);
        this.state.press === false
          ? this.setState({showPass: false, press: true})
          : this.setState({showPass: true, press: false});
      }

      showConfPass() {    
        this.state.press === false
          ? this.setState({showConfPass: false, press: true})
          : this.setState({showConfPass: true, press: false});
      }

This is actually my API for sign up section.

      onSignup() {
        const { customer_name, mobile, password, cpassword, email_address } = this.state;    
        Alert.alert('Credentials', `${customer_name} + ${mobile} + ${password} + ${cpassword} + ${email_address}`);

        fetch('url', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({  
            customer_name: this.state.customer_name,   
            mobile: this.state.mobile,
            email_address: this.state.email_address,
            password: this.state.password,      
          })    
        }).then((response) => response.json())
          .then((responseJson) => {
          alert('Success');
        }).catch((error) => {
          alert('Error');
        });
      }

      _onPress() {
        if (this.state.isLoading) return;
        this.setState({isLoading: true});
            Animated.timing(this.buttonAnimated, {
          toValue: 1,
          duration: 200,
          easing: Easing.linear,
        }).start();

        setTimeout(() => {
          this._onGrow();
        }, 2000);

        setTimeout(() => { 
          Actions.forgotpwdScree();
          this.setState({isLoading: false});
          this.buttonAnimated.setValue(0);
          this.growAnimated.setValue(0);
        }, 2300);
      }

I have added formik here . I want to show error messages during setfieldtouch,onblur and form submit

      render() {
        return (      

          <Formik initialValues= {initialValues} validationSchema={customervalidation}>
            {({ values, errors, isValid, touched, setFieldTouched, isSubmitting }) => {
              return(
                <KeyboardAvoidingView behavior="padding" style={styles.container}>
                  <View style={styles.inputcontainer}>
                    <Text style={styles.textlabel}>NAME</Text>
                    <TextInput
                      value={this.state.customer_name}
                      onChangeText={(customer_name) => this.setState({ customer_name })}
                      placeholder={'Name'}
                      style={styles.input}
                    />
                    </View>

                    <View style={styles.inputcontainer}>
                    <Text style={styles.textlabel}>PHONE NUMBER</Text>
                    <TextInput
                      value={this.state.mobile}
                      onChangeText={(mobile) => this.setState({ mobile })}
                      placeholder={'Mobile Number'}
                      style={styles.input}
                    />
                    </View>

                    <View style={styles.inputcontainer}> 
                    <Text style={styles.textlabel}>PASSWORD</Text>
                    <TextInput
                      value={this.state.password}
                      secureTextEntry={this.state.showPass}
                      onChangeText={(password) => this.setState({ password })}
                      placeholder={'PASSWORD'}
                      returnKeyType={'done'}
                      autoCapitalize={'none'}
                      autoCorrect={false}
                      style={styles.input}
                    />
                    </View>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      style={styles.btnEye}
                      onPress={this.showPass}>
                      <Image source={eyeImg} style={styles.iconEye} />
                    </TouchableOpacity>


                    <View style={styles.inputcontainer}> 
                    <Text style={styles.textlabel}>CONFIRM PASSWORD</Text>
                    <TextInput
                      value={this.state.cpassword}
                      secureTextEntry={this.state.showConfPass}
                      onChangeText={(cpassword) => this.setState({ cpassword })}
                      placeholder={'CONFIRM PASSWORD'}
                      returnKeyType={'done'}
                      autoCapitalize={'none'}
                      autoCorrect={false}
                      style={styles.input}
                    />
                    </View>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      style={styles.btnEye2}
                      onPress={this.showConfPass}>
                      <Image source={eyeImg} style={styles.iconEye} />
                    </TouchableOpacity>

                    <View style={styles.inputcontainer}>
                    <Text style={styles.textlabel}>EMAIL ID</Text>
                    <TextInput
                      value={this.state.email_address}
                      onChangeText={(email_address) => this.setState({ email_address })}
                      placeholder={'Email Address'}
                      style={styles.input}
                    />
                    </View>

                    <View style={styles.inputcontainerB}>
                    <Text style={styles.textR} >I AGREE WITH UP TERMS</Text>
                    <Button
                      large         
                      title='SIGN UP'
                      icon={{name: 'lock', type: 'font-awesome'}}
                      onPress={this.onSignup.bind(this)}
                    />           
                  </View>
                </KeyboardAvoidingView> 
              );
            }}
          </Formik>
        );
      }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用:formik组件中的render prop中的values,handleSubmit,handleChange,errors,touched,handleBlur,Formik lib已经对表单值进行了更新,因此无需为此使用状态,例如例如,对于customer_name,您需要添加一个Text组件以显示错误。

    <Formik
      initialValues={initialValues}
      onSubmit={this.onSignup}
      validationSchema={customervalidation}
      render={({
        values,
        handleSubmit,
        handleChange,
        errors,
        touched,
        handleBlur
      }) => (
       <KeyboardAvoidingView behavior="padding" style={styles.container}>
         <View style={styles.inputcontainer}>
           <Text style={styles.textlabel}>NAME</Text>
           <TextInput
             value={values.customer_name}
             onBlur={handleBlur('customer_name')}
             onChangeText={handleChange('customer_name')}
             placeholder={'Name'}
             style={styles.input}
           />
           <Text>{touched.customer_name && errors.customer_name}</Text>
         </View>
         ...
         <Button
           large         
           title='SIGN UP'
           icon={{name: 'lock', type: 'font-awesome'}}
           onPress={handleSubmit}
         />
       </KeyboardAvoidingView> 
       )
     />

handleSubmit道具会将onSubmit道具中声明的函数传递给渲染器,该渲染器将发送参数值,在您的情况下,该参数值将具有在initialValues中声明的更新值

{
      customer_name: "",
      mobile: "",
      password: "",
      repassword: "",
      email_address: "",
      company_id: "",
      profile_image: "",
      licence_number: "",
      user_status: "Active"
}