【问题标题】:How to add Email exist validation to react js based on Api resonse如何添加电子邮件存在验证以根据 Api 响应响应 js
【发布时间】:2021-01-19 12:31:29
【问题描述】:

这里显示表单字段的表单项是我的代码

import { Form, Input, Button, Select, } from 'antd';
import axios from "axios";

render() {
    const isLoading = this.state.isLoading;
    return (
        <>
            <Form className={'auth-form'} onSubmit={(e) => { this.onSubmit(e) }}>
                <h3 className={'mb-5 text-center'}>Candidate Sign Up</h3>

                <Form.Item
                    label=""
                    name="email"
                    rules={[{ required: true, type: 'email', message: 'Please enter email address'}]}
                >
                    <Input className={'ks-form-control'} placeholder={'Enter Email'} onChange={this.onChangehandler} />
                </Form.Item>
                <Form.Item
                    label=""
                    name="password"
                    rules={[{ required: true, message: 'Please input your password!' }]}
                >
                    <Input.Password className={'ks-form-control'} placeholder={'Password'} />
                </Form.Item>
                <Form.Item
                    label=""
                    name="confirmPassword"
                    rules={[{ required: true, message: 'Please confirm your password!' }]}
                >
                    <Input.Password className={'ks-form-control'} placeholder={'Confirm Password'} />
                </Form.Item>
                
                <Form.Item >
                    <Button className={'btn-custom px-4 py-2 d-block w-100'} type="primary" htmlType="submit">
                        Create an account
                    </Button>
                </Form.Item>
                
            </Form>
        </>
    )
}

这里是提交处理程序的代码。我想在 rules={[{}]}

处显示来自 api 的消息和使用以下代码的自定义消息
msg: response.data.message

提交处理程序

onSubmitHandler = (e) => {
  e.preventDefault();
    this.setState({ isLoading: true });
    axios
        .post("http://127.0.0.1:8000/api/user-signup", this.state.signupData)
        .then((response) => {
            this.setState({ isLoading: false });
            if (response.data.status === 200) {
                this.setState({
                    msg: response.data.message // message comming from api
                   
                });
               
            }

            if (response.data.status === "failed") {
                this.setState({ msg: response.data.message }); // message comming from api
                  
            }
        });
}

所有字段的验证都与 rules={[]} 一起正常工作。但是我想根据 api 响应显示错误,例如如果电子邮件已经注册,那么这将显示消息“电子邮件已存在” 请让我知道我该怎么做

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    了解什么是 Form.Item 以及您在此处使用的 UI 库会很有帮助。如果您可以在组件上设置规则,您可能还可以设置“错误”属性。我对您提供的内容的最佳猜测是:

    const [emailError, setEmailError] = useState(false)
    
    const =  onSubmit = (formvalues) => {
      const { email } = formvalues
      validateEmailViaAPI(email).then((response) => response.isValid ? doWhatEver(formvalues) : setEmailError(true))
    }
    
    const onChangeEmail = () => setEmailError(false)
    

    在您的输入组件中,您可以专门设置错误:

    <Form.Input error={emailError}>  </Form.Input>
    

    如果您自己设置错误,这应该会显示错误消息。这可能发生在组件使用的“规则”属性后面。

    不要忘记在有用的地方清除错误。如果您多次使用它,将验证放在自定义钩子中是有意义的。

    如果这没有帮助,请提供有关您正在使用的输入组件的更多信息。

    【讨论】:

    • 好吧,我的回答仍然有效。 1.:在 onSubmit 中:检查电子邮件在 then-block 中是否有效 2.:如果无效,则设置错误(但是您的表单库会这样做。我仍然不知道您在使用什么。) response.data 应该是什么。状态 === '失败' 是?我不认为那是正确的,再次检查并在 API 响应中添加一个 catch-block。然后执行类似 useState -> setError 的操作。 3. 一旦用户开始在电子邮件字段中再次输入,解决错误状态。
    【解决方案2】:

    您还没有提供onSubmit 功能,但如果您使用的是 axios,您可以执行类似的操作

    const [error, setError] = useState(null)
    
    const onSubmit = (e) => {
    e.preventDefault();
    axios.post('linkToApi').then((res) => 
    {
    `res is the response of the succesful api call`
    `do Whatever you want on successful api call`
    }).catch((err) => {
    setError(err.response.data.message)
    })
    }
    

    这里的 err.response.data 是你的 api 对错误的响应。

    您必须将后端设置为返回 http 状态代码,这将决定 api 调用的成功或失败。例如:- 200 表示成功的 api 调用,401 表示未经授权。 请参阅此答案以快速执行此操作 https://stackoverflow.com/a/28547843/12200445

    在您的表单中,您可以创建一个 div 来显示错误

    {error && <div>{error}</div>} //This div will only show when there is some value defined for `error`
    

    编辑:我没有意识到您正在使用类组件,但我希望您明白这一点。

    【讨论】:

    • 是的,我正在使用 axios。我添加了 onSubmit 功能并更新了我的问题
    • 我看起来你已经对 api 进行了一些配置以返回 http 代码。如果状态码不在 200 到 299 之间,您可以使用答案中的 axios catch 块根据 api 响应设置自定义错误消息
    • 是的,我可以,但我希望在 form.item 规则[{required: true, message: custom or message come from api response}]
    • 另一个建议是在package.json 文件中设置代理,以避免在 axios 函数中写入整个 url,这将更容易开发和部署。看到这个-dev.to/loujaybee/using-create-react-app-with-express
    • form.item 来自哪里??
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2021-12-25
    • 1970-01-01
    • 2016-09-30
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多