PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     antd, forms, input, reactjs, trim     No comments   

Issue

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



Answered By - Scratch'N'Purr
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing