1

I have a user requirement when adding a form it should check if the name of the form is already exist. How can I do that in es6? I'm using AntDesign and ReactJS.

Here's my code

<Form.Item label="Form Name">
  {getFieldDecorator('formName', {
   rules: [formConfig],
  })(<Input name="formName" onChange={onChange} />)}
</Form.Item>
const handleChange = e => {
  const { name, value } = e.target;

   setState(() => ({
     ...state,
     [name]: value,
   }));

   let isExist = [...formDataSource];
    let foundExistItem = isExist.filter(
      item => item.formName === formName
    );
 };
Alyssa Reyes
  • 2,389
  • 6
  • 27
  • 52
  • Are all form names local, or stored? – zfrisch Oct 08 '19 at 15:38
  • @zfrisch it will be posted in API – Alyssa Reyes Oct 08 '19 at 15:40
  • What do you want to check, if the label `Form Name` in `Form.Item` exists or the field `formName` in `Form`? – Dennis Vash Oct 08 '19 at 15:45
  • @DennisVash the field name. getting the list from the api then check if the data exist show the validation. Else, it will be successfully added – Alyssa Reyes Oct 08 '19 at 15:50
  • Your question is unclear so I will elaborate: are fields like `formName` added **Dynamically** and that's why you want to check if it exists **or** you want to check if the `Input` inside `formName` is not empty? – Dennis Vash Oct 08 '19 at 15:54
  • And yes you can check it, I just trying to figure out what exactly you asking so I can answer properly. – Dennis Vash Oct 08 '19 at 15:55
  • @DennisVash yes. formName added dynamically. Sorry for the unclear question. Basically I want to check if I have existing data in my API while typing in the input field. For example for emails, It will not allow the user to create a new email if it's already exist. – Alyssa Reyes Oct 08 '19 at 15:59
  • Ok, I'll add an answer soon – Dennis Vash Oct 08 '19 at 16:02

1 Answers1

0

If you want dynamically query the form fields, you should wrap your form with Form.create.

It injects useful functionalities like onFieldsChange listener:

const onFieldsChange = (_, changedFiels) => {
  const { username } = changedFiels;
  if (username) {
    // Make your API checks
    console.log(`Now changing ${username.name}`);
  }
};

const ValidatedFields = Form.create({ onFieldsChange })(App);

Note: You should keep your Form.Items uncontrolled using getFieldDecorator therefore avoiding onChange while collecting form data.

If you still insist to make form items controlled, you should use getFieldValue:

const handleChange = e => {
  const { name, value } = e.target;
  const { getFieldValue } = form;

  setState(() => ({
    ...state,
    [name]: value
  }));

  // or use getFieldValue for a single query
  const values = getFieldsValue(['formName',...more fields]);

  if (values.length) {
    // API CALL
  }
};

Edit Q-58289639-FormFieldValidate

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118