Skip to main content

Yup

安裝Yup

npm install yup

使用Yup

  • 定義一個validationSchema,然後交給Formik來執行
import React from 'react';
import {TextInput, Button} from 'react-native';
import {Formik} from 'formik';
import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
email: Yup.string().required().email().label("Eamil"),
password: Yup.string().required().min(4).label("Password")
});

const MyScreen = () => {
return (
<View>
<Formik
initialValues={{email:'', password:''}}
onSubmit={(values) => console.log(values)}
validationSchema={validationSchema}
>
{({handleChange, handleSubmit, errors}) => (
<>
<TextInput onChangeText={handleChange('email')}>
<Text style={{color:'red'}}>{errors.email}</Text>
<TextInput onChangeText={handleChange('password')}>
<Text style={{color:'red'}}>{errors.password}</Text>
<Button onPress={handleSubmit}>
</>
)}

</Formik>
</View>
);
}

export default MyScreen;