Reputation: 1178
I am trying to limit the user input as one enters some value in the
form item input field. I want the user to just add limited characters and
after that the user is not able to type any characters and additional
characters are replaced with ''
.
So far Im using Ant Design Forms in my react application. I am not handling form data manually since Im using Form.create
and getFieldsDecorator
which will collect and validate Form data automatically as stated in the documentation.
The documentation says to use setFieldsValue
to set control's value programmaticly.
In my case it doesn't seem to work. I am mentioning only the important parts of code for the sake of simplicity here.
const Modal = ({
visible,
modalType,
closeModal,
companiesList,
cohortsList,
employeeDetail,
inProgressAction,
success,
...props
}) => {
const [editForm, setEditForm] = useState(INITIAL_STATE);
const handleChange = name => event => {
const value = event.target.value.slice(0,10);
setEditForm(prevEditForm => ({
...prevEditForm,
[name]: value,
}));
props.form.setFieldsValue({ [name]: value }); // This doesn't limit the value to 10 and the user is still able to enter more than 10 charavters
};
return (
<Modal
title="Create New Employee"
visible={visible}
onOk={handleOk}
onCancel={closeModal}
destroyOnClose
centered
footer={[
<Button
key="cancel"
onClick={closeModal}
>
Cancel
</Button>,
<Button
key="submit"
type="primary"
onClick={handleOk}
disabled={!isSubmitEnabled()}
loading={inProgressAction === 'add'}
>
Add Employee
</Button>,
]}
>
<Spin
spinning={props.loadingCompanies || props.loadingCohorts}
className="mk_dotted_spinner"
size="small"
>
<Form {...formItemLayout}>
<Form.Item label="Name">
{props.form.getFieldDecorator('fullName', {
initialValue: editForm.fullName,
rules: [
{
required: true,
message: 'Please input employee name!',
},
],
})(
<Input
className="mk_input_secondary"
onChange={handleChange('fullName')}
/>
)}
</Form.Item>
</Form>
</Spin>
</Modal>
);
};
export default Form.create({ name: 'employeeForm' })(Modal);
The expected behavior is that user cannot enter more than 10 characters in the field since I am setting setFieldsValue
and slicing the input but the user is still able to enter input. Somehow, my understanding is since getFieldsDecorator
is controlling the form I am unable to limit the input. Is there some workaround for this? I have been looking at the documentation regarding setFieldsValue
but couldn't find anything except this line
Use setFieldsValue to set other control's value programmaticly.
Which is Not working. Here is the documentation link, I have been following.
Any help would be greatly appreciated. Thanks.
Upvotes: 2
Views: 1995
Reputation: 11
You can simply put maxLength={10} in the input tag
<Input
maxLength={10}
className="mk_input_secondary"
onChange={handleChange('fullName')}
/>
Upvotes: 1