Search code examples
javascriptreactjsantd

antd: Force an Input field to Uppercase


i want the text to be upeercase with ant design, i tried this:

<Form form={form} layout='vertical' autoComplete='off'>
    <Form.Item
      name='apellido_empleado'
      label='Apellidos'
      rules={[
        {
          required: true,
          message: 'Por favor ingrese los apellidos',
          transform: (v) => v.toUpperCase(),
        },
      ]}>
      <Input />
    </Form.Item>

it seems that the property transform only work for validations.


Solution

  • You can use onInput event to transform text to uppercase.

    const [form] = Form.useForm<{ apellido_empleado: string }>();
    return (
        <>
            <Form form={form} layout='vertical' autoComplete='off' sub>
                <Form.Item
                    name='apellido_empleado'
                    label='Apellidos'
                    rules={[
                        {
                            required: true,
                            message: 'Por favor ingrese los apellidos'
                        },
                    ]}>
                    <Input onInput={e => e.target.value = e.target.value.toUpperCase()} />
                </Form.Item>
            </Form>
            <Button onClick={() => console.log(form.getFieldValue('apellido_empleado'))}>Print value</Button>
        </>
    );
    

    In typescript (e.target as HTMLInputElement).value