反应表单验证

时间:2020-10-14 13:23:22

标签: javascript reactjs

我有一个用于注册的多步骤表单。表单验证最简单,最好的方法是什么?我应该使用什么?使用Formik可以吗?你能建议我做什么吗? 这是其中一种形式:

return(
<Container>
  <Row className="justify-content-center">
    <Col md="8">
      <Card border="dark">
        <Card.Title className="text-center">New User</Card.Title>
        <Card.Body>
          <Form>
            <Form.Group controlId="formGridFirstName">
              <Form.Label>First Name</Form.Label>
              <Form.Control type="text" value={formValues.firstName} onChange={handleChange('firstName')} />
            </Form.Group>

            <Form.Group controlID="formGridLastName">
              <Form.Label>Last Name</Form.Label>
              <Form.Control type="text" value={formValues.lastName} onChange={handleChange('lastName')} />
            </Form.Group>

            <Form.Group controlID="formGridEmail">
              <Form.Label>Email</Form.Label>
              <Form.Control type="email" value={formValues.email}  onChange={handleChange('email')} />
            </Form.Group>

            <Form.Group controlId="formGridPassword">
              <Form.Label>Password</Form.Label>
              <Form.Control type="password" value={formValues.password}  onChange={handleChange('password')} />
            </Form.Group>

            <Form.Group controlId="formGridPhone">
              <Form.Label>Phone</Form.Label>
              <Form.Control type="tel" value={formValues.phone} onChange={handleChange('phone')} />
            </Form.Group>

            <Button variant="light" type="submit" size="lg" onClick={redirectToHome}>Cancel</Button>
            <Button variant="primary" type="submit" size="lg" onClick={saveAndContinue}>Next</Button>
          </Form>
        </Card.Body>
      </Card>
    </Col>
  </Row>
</Container>

); };

2 个答案:

答案 0 :(得分:0)

您可以使用 Formik Yup 进行验证:

https://formik.org/docs/api/formik#validationschema-schema----schema

npm链接:

https://www.npmjs.com/package/formik

https://www.npmjs.com/package/yup

它看起来像这样:

export default function MyForm() {
  const initValues = {
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    phone: ""
  };
  const schema = Yup.object().shape({
    firstName: Yup.string(),
    lastName: Yup.string(),
    email: Yup.string().email("Email format is invalid."),
    password: Yup.string()
      .required("No password provided.")
      .min(8, "Password is too short - should be 8 chars minimum.")
      .matches(/[a-zA-Z]/, "Password can only contain Latin letters."),
    phone: Yup.string().phone(" ")
  });

  return (
    <Formik validationSchema={schema} initialValues={initValues}>
      {props => {
        const {
          values,
          touched,
          errors,
          isSubmitting,
          handleChange,
          setFieldTouched
        } = props;
        return (
          <Container>
            <Row className="justify-content-center">
              <Col md="8">
                <Card border="dark">
                  <Card.Title className="text-center">New User</Card.Title>
                  <Card.Body>
                    <Form>
                      <Form.Group controlId="formGridFirstName">
                        <Form.Label>First Name</Form.Label>
                        <Form.Control
                          name="firstName"
                          type="text"
                          value={values.firstName}
                          onChange={handleChange}
                          setFieldTouched={setFieldTouched}
                          errors={errors}
                        />
                      </Form.Group>

                      <Form.Group controlID="formGridLastName">
                        <Form.Label>Last Name</Form.Label>
                        <Form.Control
                          name="lastName"
                          type="text"
                          value={values.lastName}
                          onChange={handleChange}
                          setFieldTouched={setFieldTouched}
                          errors={errors}
                        />
                      </Form.Group>

                      <Form.Group controlID="formGridEmail">
                        <Form.Label>Email</Form.Label>
                        <Form.Control
                          name="email"
                          type="email"
                          value={values.email}
                          onChange={handleChange}
                          setFieldTouched={setFieldTouched}
                          errors={errors}
                        />
                      </Form.Group>

                      <Form.Group controlId="formGridPassword">
                        <Form.Label>Password</Form.Label>
                        <Form.Control
                          name="password"
                          type="password"
                          value={values.password}
                          onChange={handleChange}
                          setFieldTouched={setFieldTouched}
                          errors={errors}
                        />
                      </Form.Group>

                      <Form.Group controlId="formGridPhone">
                        <Form.Label>Phone</Form.Label>
                        <Form.Control
                          name="phone"
                          type="tel"
                          value={values.phone}
                          onChange={handleChange}
                          setFieldTouched={setFieldTouched}
                          errors={errors}
                        />
                      </Form.Group>

                      <Button
                        variant="light"
                        type="submit"
                        size="lg"
                        onClick={redirectToHome}
                      >
                        Cancel
                      </Button>
                      <Button
                        variant="primary"
                        type="submit"
                        size="lg"
                        onClick={saveAndContinue}
                      >
                        Next
                      </Button>
                    </Form>
                  </Card.Body>
                </Card>
              </Col>
            </Row>
          </Container>
        );
      }}
    </Formik>
  );
}

但是您还应该更改Form.Control组件:

添加

import { ErrorMessage, getIn } from "formik";
const error = getIn(props.errors, props.name);

并将这些属性添加到您的输入

onChange={(e) => {setFieldTouched("firstName");handleChange(e);}
error={error}

和显示错误

<Error component="div" name={props.name} />

答案 1 :(得分:0)

我建议添加您自己的验证器并捆绑相同类型的输入。例如,“名字”和“姓氏”都是字符串,因此您可以使用字符串类型的验证器。你可以这样做

//validator.js

const stringValidator = (value) => {
   if(isEmpty(value)){
     return { isValid: false, errors: ["Field cannot be blank"] }
   } 
   return { isValid: true, errors: [] } 
}

const config = {
   firstName: stringValidator,
   lastName: stringValidator,
   email: emailValidator,
   cellphone: cellphoneValidator,
   password: passwordValidator
}

const getValidator = (questionId) => config[questionId];

export default (questionId, value) => {
   const validate = getValidator(questionId);
   return validate(value)
}

...
// Form.js class

answerQuestion(questionId){
   return (e) => {
     const answer = e.target.value;
     const validation = validate(questionId, answer)
     const { errors } = validation;
     let { fields } = this.state;
     fields[questionId] = { errors, value, label: field.label }
     this.setState({ fields })
   }
}

...

<Form>
   {this.state.fields.map( field => {
     return( 
         <Form.Group>
          <Form.Label>{field.label}</Form.Label>
          <Form.Control type="text" value={field.value} onChange={this.answerQuestion(field.questionId)} />
          {field.errors.map(err => <span>{err}</span>} 
        </Form.Group>
     )
   }
</Form>