验证不好时,如何做出本地警报而不是错误消息

时间:2019-03-25 17:59:34

标签: validation react-native formik

我正在处理带有formik的react-native表单,但是我对验证有疑问, 我希望将验证发送到Alert.alert(errorMessage),而不是发送到文本机器人上,例如<Text>{errorMessage}</Text>。 这是我的实际形式:

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>
    );
  }
}

如果您知道其他任何可以进行表单验证并且可以使用Alert.alert压缩的库,我就准备好了。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以在验证formik属性时触发警报消息。

这样做。

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}
>