【问题标题】:how to add validation to a reactjs form如何向 reactjs 表单添加验证
【发布时间】:2023-01-19 20:09:39
【问题描述】:

我已经开发了一个注册表,我尝试使用验证格式,但它不起作用。我不知道如何以及在何处为其编写函数并应用它。请帮我怎么做。我将附上我到目前为止所做的代码。

import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router';

export default function Create() {
    let navigate = useNavigate();
    const [Employee_name, setEmployee_name] = useState('');
    const [Employee_id, setEmployee_id] = useState('');
    const [Employee_address, setEmployee_address] = useState('');
    const [Employee_post, setEmployee_post] = useState('');



    const postData = () => {

        axios.post(`http://localhost:5000/qo`, {
            Employee_name,
            Employee_id,
            Employee_address,
            Employee_post

        }).then(() => {
            navigate('/read')
        })
        alert('Data Saved')
    }
    return (
        <div>
            <Form className="create-form">
                <Form.Field required={true}>
                    <label>Employee Name</label>
                    <input placeholder='Employee Name' onChange={(e) => setEmployee_name(e.target.value)} required={true}/>
                </Form.Field>
                <Form.Field required={true}>
                    <label>Employee ID</label>
                    <input placeholder='Employee ID' onChange={(e) => setEmployee_id(e.target.value)} required={true}/>
                </Form.Field>
                <Form.Field required={true}>
                    <label>Employee Address</label>
                    <input placeholder='Employee Address' onChange={(e) => setEmployee_address(e.target.value)} required={true}/>
                </Form.Field>
                <Form.Field required={true}>
                    <label>Employee Position</label>
                    <input placeholder='Employee Position' onChange={(e) => setEmployee_post(e.target.value)} required={true}/>
                </Form.Field>
                <Button onClick={postData} type='submit'>Submit</Button>
            </Form>
        </div>
    )
}

【问题讨论】:

标签: javascript reactjs jsform


【解决方案1】:

那里有很好的库,可以帮助您在允许用户提交表单之前进行表单验证。

一个这样的库可以是 formik 和 Yup。

这是我在表单上进行客户端表单验证的方式:

登录模式(用 Yup 制作):

import * as Yup from 'yup';


const loginSchema = Yup.object().shape({
    username: Yup.string()
        .min(3, 'Minimum 3 chars')
        .max(50, 'Max 50 chars')
    /* password: Yup.string()
        .min(6, 'Minimum 6 chars')
        .max(50, 'Max 50 chars')
    */
});

登录组件:

export const Login = () => {

    const [loading, setLoading] = useState(false);


    const formik = useFormik({
        initialValues: {
            username: ''
        },
        validationSchema: loginSchema,

        onSubmit: async (values, {setStatus, setSubmitting}) => {
            setLoading(true);
            setStatus(null);

            try {

                  // Call your API function to post to the backend here
                  // You can access your form values in the "values" parameter

                    setLoading(false);

            } catch (error) {
                console.error(error);
                setStatus('User not found');
                setSubmitting(false);
                setLoading(false);
            }
        }
    });

}

return (
        <form
            onSubmit={formik.handleSubmit}
            className={'auth-form-wrapper'}
        >

            {/* begin::Heading */}
            <div className={'auth-form-header'}>
                <h1>Log in</h1>
                <div className={'auth-error-message-container'}>
                        formik.status && (
                            <p className={'error-message'}>{formik.status}</p>
                        )
                    }
                </div>
            </div>
            {/* end::Heading */}

            {/* begin::Form group content */}
            <div className={'auth-form-content'}>
                {/* begin::Form group */}
                <div className={'dynamic-input-container'}>
                    <input type='text'
                           id="username"
                           value={formik.values.username}
                           onChange={formik.handleChange}
                           placeholder='Username'
                           className={'dynamic-input auth-input ' + clsx(
                               {'is-invalid': formik.touched.username && formik.errors.username},
                               {
                                   'is-valid': formik.touched.username && !formik.errors.username
                               }
                           )}
                           autoComplete='off'
                    />

                    {formik.touched.username && formik.errors.username && (
                        <div className='fv-plugins-message-container'>
                            <span role='alert'>{formik.errors.username}</span>
                        </div>
                    )}
                </div>
                {/* end::Form group*/}

                {/* begin::Action */}
                <div className='auth-btn-container'>
                    <Button variant="contained" size="medium" type={'submit'} disabled={loading}>
                        {
                            !loading ? <span>Continue</span>
                                :
                                (
                                    <span className={'auth-spinner-container'}>
                        <ClipLoader
                            loading={loading}
                            size={20}
                            aria-label='Loading Spinner'
                        />
                        </span>
                                )
                        }
                    </Button>
                </div>
                {/* end::Action */}
            </div>
            {/* end::Form group content */}

        </form>
    );

请注意,在我的示例中,我只有一个“用户名”输入,但您显然可以添加任意数量的字段。

文档:

福米克:https://formik.org/docs/tutorial

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

clxs:https://www.npmjs.com/package/clsx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 2021-08-06
    • 2013-09-18
    • 2012-09-16
    • 2022-12-18
    • 2019-01-06
    • 2019-05-06
    • 2016-09-05
    相关资源
    最近更新 更多