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

Time:08-03

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

CodePudding user response:

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

CodePudding user response:

Instead of trimming onChange, do that in an onBlur callback: formatInput = (event) => { const attribute = event.target.getAttribute('name') this.setState({ [attribute]: event.target.value.trim() }) }

or when you click enter onKeyPress={(e) => {if (e.key === "Enter") {setValue(e.target.value.trim())} }}

CodePudding user response:

you can do like this instead of using trim()

import React, { useState } from 'react';
import 'antd/dist/antd.css';
import { Form, Input } from 'antd';


const App = () => {
  const [inputValue, setValue] = useState({input1: '', input2: '', input3: ''});
  const onFinish = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const handleOnChange = (e) => {
    let {value} = e.target;
    let data = {...inputValue};
    if (value.length && value[0] === ' ') {
      data[e.target.name] = '';
      setValue(data);
      return;
    }
    data[e.target.name] = value;
    setValue(data);
  }

  return (
    <Form
      name="basic"
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 16,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <>
        <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 name="input1" value={inputValue.input1} onChange={handleOnChange} />
        </Form.Item>

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

        <Form.Item
          label={t("forms.inputs.Company.label")}
          rules={[
            {
              required: true,
              message: t("forms.inputs.Company.rules.required"),
            },
          ]}>
          <Input name="input3" value={inputValue.input3} onChange={handleOnChange} placeholder={t("forms.inputs.currentCompany.placeholder")} />
        </Form.Item>
      </>
    </Form>
  );
};

export default App;
  • Related