how can I show customized error messaged from server side validation in React Admin package?

后端 未结 4 1418
栀梦
栀梦 2020-12-16 18:22

Is there any way to perform server side form validation using https://github.com/marmelab/react-admin package?

Here\'s the code for AdminCreate Component. It sends c

4条回答
  •  既然无缘
    2020-12-16 18:38

    Found a working solution for react-admin 3.8.1 that seems to work well.

    Here is the reference code

    https://codesandbox.io/s/wy7z7q5zx5?file=/index.js:966-979

    Example:

    First make the helper functions as necessary.

    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
    const simpleMemoize = fn => {
      let lastArg;
      let lastResult;
      return arg => {
        if (arg !== lastArg) {
          lastArg = arg;
          lastResult = fn(arg);
        }
        return lastResult;
      };
    };
    

    Then the actual validation code

    const usernameAvailable = simpleMemoize(async value => {
      if (!value) {
        return "Required";
      }
      await sleep(400);
      if (
        ~["john", "paul", "george", "ringo"].indexOf(value && value.toLowerCase())
      ) {
        return "Username taken!";
      }
    });
    

    Finally wire it up to your field:

    const validateUserName = [required(), maxLength(10), abbrevUnique];

    const UserNameInput = (props) => {
        return (
            
            );
    }
    

提交回复
热议问题