最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - show min and max length form validation error in react? - Stack Overflow

matteradmin4PV0评论

I am using the package below to generate a form dynamically:

I have generated a simple login-form using this link

After building, it creates a JSON. Then, I generate a form using that JSON.

I want to show custom messages like required field and min length error message and max length error message

ReactDOM.render(
  <Form
    src={{
      display: "form",
      ponents: [
        {
          label: "Name",
          validate: {
            required: true,
            json: {
              if: [
                {
                  "===": [
                    {
                      var: "data.name"
                    },
                    ""
                  ]
                },
                true,
                "required!"
              ]
            },
            minLength: 5,
            maxLength: 15
          },
          key: "name",
          type: "textfield",
          input: true
        },
        {
          type: "button",
          label: "Submit",
          key: "submit",
          //  disableOnInvalid: true,
          input: true
        }
      ]
    }}
    options={{ noAlerts: true }}
    onSubmit={i => {
      alert(JSON.stringify(i.data));
    }}
  />,

  // <Form src="" onSubmit={(i)=>{console.log(i)}} />,
  rootElement
);

I am using the package below to generate a form dynamically:

https://www.npmjs./package/react-formio

I have generated a simple login-form using this link https://codesandbox.io/s/cra-react-formio-iy8lz

After building, it creates a JSON. Then, I generate a form using that JSON.

https://codesandbox.io/s/quirky-chatelet-5ujhj

I want to show custom messages like required field and min length error message and max length error message

ReactDOM.render(
  <Form
    src={{
      display: "form",
      ponents: [
        {
          label: "Name",
          validate: {
            required: true,
            json: {
              if: [
                {
                  "===": [
                    {
                      var: "data.name"
                    },
                    ""
                  ]
                },
                true,
                "required!"
              ]
            },
            minLength: 5,
            maxLength: 15
          },
          key: "name",
          type: "textfield",
          input: true
        },
        {
          type: "button",
          label: "Submit",
          key: "submit",
          //  disableOnInvalid: true,
          input: true
        }
      ]
    }}
    options={{ noAlerts: true }}
    onSubmit={i => {
      alert(JSON.stringify(i.data));
    }}
  />,

  // <Form src="https://peb3z.sse.codesandbox.io/abc" onSubmit={(i)=>{console.log(i)}} />,
  rootElement
);
Share Improve this question asked Nov 3, 2019 at 6:37 user944513user944513 12.8k52 gold badges185 silver badges348 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

I think instead of using JSON logic you can write custom validate method in react-formio. Where based on the condition you can add your logic. Code :

import React from "react";
import ReactDOM from "react-dom";
import { FormBuilder } from "react-formio";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <FormBuilder
        form={{
          ponents: [
            {
              input: true,
              tableView: true,
              inputType: "text",
              inputMask: "",
              label: "First Name",
              key: "firstName",
              placeholder: "Enter your first name",
              prefix: "",
              suffix: "",
              multiple: false,
              defaultValue: "",
              protected: false,
              unique: false,
              persistent: true,
              validate: {
                required: false,
                minLength: "",
                maxLength: "",
                pattern: "",
                custom: "valid =  (input.length< 5)  ? 'Your input must be greater than 5':(input.length> 20) ? \n\"Your input must be less than 20\" \n : true;", //Your custom logic code
                customPrivate: false
              },
              conditional: {
                show: false,
                when: null,
                eq: ""
              },
              type: "textfield"
            },
            {
              input: true,
              tableView: true,
              label: "Message",
              key: "message",
              placeholder: "What do you think?",
              prefix: "",
              suffix: "",
              rows: 3,
              multiple: false,
              defaultValue: "",
              protected: false,
              persistent: true,
              validate: {
                required: false,
                minLength: "",
                maxLength: "",
                pattern: "",
                custom: ""
              },
              type: "textarea",
              conditional: {
                show: false,
                when: null,
                eq: ""
              }
            },
            {
              type: "button",
              theme: "primary",
              disableOnInvalid: true,
              action: "submit",
              block: false,
              rightIcon: "",
              leftIcon: "",
              size: "md",
              key: "submit",
              tableView: false,
              label: "Submit",
              input: true
            }
          ],
          display: "form"
        }}
        onChange={schema => console.log(schema)}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);



Here is the demo: https://codesandbox.io/s/cra-react-formio-niq10

I would rather suggest instead of creating your own form create from there server and it should be easy to plug and play. Adding like this JSON there are chances mistakes can happen.

Couple of suggestions.

You should use form attribute instead of a src attribute. While the posted code has the correct syntax, the codesandbox still uses.

<FormBuilder
        src={{}} />

As mentioned by @ShubhamVerma, you should use custom javascript validation.

Also as this is the second question you are asking regarding formio, I'm not sure how you are creating the JSON.

You should go to the validation tab of a ponent and you can see the different options available, that you can play around with. In your case you can enter validation script in the custom validation section. The section also describes all the variables available for access.

if (input.length === 0){
  valid = "You should enter something";
}
else{
  if(input.length < 3){
    valid = `Min length is 3`;
  }else if (input.length > 15){
    valid  = `Max length is 15`
  }else{
    valid = true
  }
} 

Also note that you might have to override the css to display the form errors placeholder. Looks like bootstrap is setting it to display:none.

styles.css

.formio-errors.invalid-feedback {
  display: block;
} 

Demo

If the form customization tabs don't open from codesandbox embedded browser, try to open in a new window.

..............................................................................................................................

Post a comment

comment list (0)

  1. No comments so far