Reputation: 681
I'm working on a react-native form whith formik and i have a problem with validation,
I want the validation to be send to an Alert.alert(errorMessage)
and not on a text bot like this <Text>{errorMessage}</Text>
.
This is my actual form :
import { View, Text, StyleSheet } from "react-native";
import { Formik } from "formik";
import yup from "yup";
import SubmitButton from "../buttons/Submit";
import LoginInput from "../inputs/Login";
interface values {
email: string;
password: string;
}
interface props {
onSubmit: (string: values) => void;
validate: (values: values) => void;
isFetching: boolean;
}
const styles = StyleSheet.create({
container: {
marginTop: 39,
padding: 20,
justifyContent: "center",
alignItems: "center"
}
});
export default class AuthenticationForm extends Component<props, {}> {
render() {
const { onSubmit, validate, isFetching } = this.props;
return (
<View style={styles.container}>
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={onSubmit}
validationSchema={yup.object().shape({
email: yup
.string()
.email()
.required(),
password: yup.string().required()
})}
>
{(props: any) => (
<View style={{ marginTop: 75 }}>
<LoginInput
autoCapitalize="none"
returnKeyType="done"
placeholder=""
value={props.values.email}
onChangeText={props.handleChange("email")}
secureTextEntry={false}
autoCorrect={false}
topText={"email :"}
errorMessage={props.errors.email}
/>
<LoginInput
returnKeyType="done"
autoCapitalize="none"
secureTextEntry
placeholder=""
autoCorrect={false}
value={props.values.password}
onChangeText={props.handleChange("password")}
topText={"password :"}
/>
<SubmitButton onPress={props.handleSubmit} loading={isFetching} />
</View>
)}
</Formik>
</View>
);
}
}
If you know of any other lib that allows you to do form validation and that are compactible with Alert.alert I am a ready.
Thank you for you help !
Upvotes: 1
Views: 1798
Reputation: 1154
You can trigger alert messages inisde validate prop of formik.
do it like this.
onValidate = values => {
let errors = {};
if (!values.email) {
alert('Required')
//you can alert anywhere on this scope
errors.email = 'Required';
} else if (// some regex condition) {
alert('Invalid email address')
errors.email = 'Invalid email address';
}
//...
return errors;
};
<Formik
initialValues={{ email: "", password: "" }}
validate={this.onValidate}
// add here
onSubmit={this.onSubmit}
>
Upvotes: 1