Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Trim White Spaces from input field in ant-design form?

I have a form with ant design. I want to add a rule for each input field that the user can't enter spaces to fill the input. (spaces forbidden)

I try this method { transform: (value) => value.trim() }but it doesn't work.

I appreciate your help.

<>
  <Form.Item
    label={t("forms.inputs.Name.label")}
    rules={[
      {
        required: true,
        message: t("forms.inputs.Name.rules.required"),
      },
      {
        min: 3,
        message: t("forms.inputs.Name.rules.minLength"),
      },
    ]}>
    <Input />
  </Form.Item>

  <Form.Item
    label={t("forms.inputs.job.label")}
    rules={[
      {
        required: true,
        message: t("forms.inputs.job.rules.required"),
      },
    ]}>
    <Input />
  </Form.Item>

  <Form.Item
    label={t("forms.inputs.Company.label")}
    rules={[
      {
        required: true,
        message: t("forms.inputs.Company.rules.required"),
      },
    ]}>
    <Input placeholder={t("forms.inputs.currentCompany.placeholder")} />
  </Form.Item>
</>
like image 946
Negin Avatar asked Oct 24 '25 19:10

Negin


2 Answers

Just set the whitespace property to true in the rule like so. (Reference)

{
    required: true,
    whitespace: true,
    message: "Required"
}
like image 98
D.B.P. Avatar answered Oct 27 '25 09:10

D.B.P.


Just write a custom validation rule:

<Form.Item
  label="Username"
  name="username"
  rules={[
    {
      required: true,
      message: "Required"
    },
    {
      validator: (_, value) =>
        !value.includes(" ")
          ? Promise.resolve()
          : Promise.reject(new Error("No spaces allowed"))
    }
  ]}
>
  <Input />
</Form.Item>

For email validation, you can use the following regex pattern:

<Form.Item
  label="Email"
  name="email"
  rules={[
    {
      required: true,
      message: "Required"
    },
    {
      pattern: /([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\"([]!#-[^-~ \t]|(\\[\t -~]))+\")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])/,
      message: "Invalid email"
    }
  ]}
  normalize={(value, prevVal, prevVals) => value.trim()}
>
  <Input />
</Form.Item>

DEMO

like image 42
Scratch'N'Purr Avatar answered Oct 27 '25 09:10

Scratch'N'Purr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!