Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant-Design form validate returns old values while using onChange

I am using ant-design Form Item like this:

 {getFieldDecorator('city', {initialValue:'a', rules: [{required:true,message:' '}]})(
     <select onChange={onChange}  className="form-control">
     <option  value='a' >a</option>
     <option  value='b' >b</option>
     </select>
                            }



and here is my onchange function:




onChange=()=>{
 form.validateFields((err, values) => {
            console.log(values)



        })
}

The problem is that while changing value to 'b', I still get 'a' as the form value in onChange function (console.log(values)). This happens while changing value from 'b' to 'a' too.

like image 222
Hadi Ranjbar Avatar asked Jan 28 '26 17:01

Hadi Ranjbar


1 Answers

You are mixing up immediate onChange behaviour with validation. If you are looking for a dropdown with immediate action you do not need a <Form>, just use the <Select> by itself.

If you want a proper form with a submit function, you should not use onChange on the <Select> at all, that is handled automatically by antd. And then you will have proper values when you call form.validateFields at form submit time.

Finally, if you do want immediate actions using field validation inside a <Form>, use the onFieldsChange option rather than individual widget onChange.

like image 84
Jesper We Avatar answered Jan 31 '26 06:01

Jesper We