Search code examples
reactjsformsinputantdtrim

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

Solution

  • 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