1

item at form to show up form fields here is my code

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

Here is the code for submithandler. I want to show message comming from api and custom message with below code at rules={[{}]}

msg: response.data.message

On submit handler

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

The valiations for all fields working fine with rules={[]} . But I want show error based on api response like if a email already registered then this will show message 'email already exists' Please let me know how can i do this

mdkamrul
  • 274
  • 1
  • 13

2 Answers2

0

It would be helpful to know what Form.Item even is, which UI library you are using here. If you can set rules on the component you can probably also set an "error"-attribute. My best guess to what you have provided would be:

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)

Inside your Input Component you can specifically set the error:

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

This should then show the error message if you set the error yourself. This probably happened behind the "rules"-attribute that the component used.

Dont forget to clear the error at a useful point. It would make sense to put that validation inside a custom hook if you use it more than once.

If this wasnt helpful please provide more input about the Input-Component that you are using.

Chrissi Grilus
  • 1,099
  • 2
  • 9
  • 21
  • Well my answer is still valid. 1.: In onSubmit: check if the email is valid in the then-block 2.: If not valid set the error (however your form library does it. I still dont know what you are using.) What should response.data.status === 'failed' be? I dont think thats correct, check again and add a catch-block in the API-response. Then do something like useState -> setError. 3. resolve the error state once the user starts typing again in the email field. – Chrissi Grilus Oct 05 '20 at 10:46
0

You have not provided the onSubmit function but if you are using axios you can do something like

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

Here err.response.data is the response of your api on error.

You have to set your backend to return http status codes which will determine the success or failure of the api call. For eg:- 200 means successful api call and 401 means unauthorized. See this answer to do this in express https://stackoverflow.com/a/28547843/12200445

In your form you can create a div to show the error

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

EDIT: I didn't realize you were using class components but I hope you get the idea.

Deepak Gupta
  • 614
  • 1
  • 7
  • 14
  • Yes, I am using axios. I have added onSubmit function and updated my question – mdkamrul Oct 05 '20 at 04:42
  • I looks like you have somewhat configured the api to return http codes. You can use the axios catch block as in the answer to set custom error message based on api response if the status code is not between 200 and 299 – Deepak Gupta Oct 05 '20 at 05:27
  • yes i can but i wanted this at form.item rules[{required: true, message: custom or message came from api response}] – mdkamrul Oct 05 '20 at 05:34
  • Another suggestion for you to set up a proxy in your `package.json` file to avoid writing the whole url in the axios function which will development and deployment easier. See this- https://dev.to/loujaybee/using-create-react-app-with-express – Deepak Gupta Oct 05 '20 at 05:36
  • Where does form.item come from ?? – Deepak Gupta Oct 05 '20 at 05:37
  • import { Form, Input, Button, Select, } from 'antd'; – mdkamrul Oct 05 '20 at 05:40
  • "antd": "^4.6.6", – mdkamrul Oct 05 '20 at 05:45
  • I don't know much about antd. You should have mentioned it in the question. I dont think you can set this up in rules. There must be some another way to show validation messages in antd. You should see their documentation. – Deepak Gupta Oct 05 '20 at 05:59