egg-yup

0.0.3 • Public • Published

egg-yup

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Base on yup

Install

$ npm i egg-yup --save

or

$ yarn add egg-yup

Usage

// {app_root}/config/plugin.js
exports.yup = {
  enable: true,
  package: 'egg-yup',
};

Configuration

// {app_root}/config/config.default.js
exports.yup = {
  locale: 'zh-CN', // default null
  locales: { // default {}
    'zh-CN': {
      number: {
        min: '${path} 不能小于 {$min}'
      }
    }
  },
  options: { // ref: https://github.com/jquense/yup#mixedvalidatevalue-any-options-object-promiseany-validationerror
    strict: false;
    abortEarly: true;
    stripUnknown: false;
    recursive: true;
    context: null;
  },
  onerror: (err, ctx) => { // default null
    ctx.throw(422, 'Validation Failed', {
      errors: err.errors,
    });
  },
};

see config/config.default.js for more detail.

Example

// app/controller/user.js#register
 
const { ctx, app: { yup } } = this;
 
await ctx.validate({
  nickname: yup.string()
    .required('nickname is required')
    .matches(/^[a-z0-9]{4,12}$/, 'nickname invalid')
    .test('uniqueNickname', 'nickname already taken', value => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(value === 'test');
        }, 0);
      });
    }),
  password: yup.string()
    .required()
    .matches(/^[a-z]{6,16}$/, 'password invalid'),
  age: yup.number().min(18).max(80),
});

Api reference

app.yup

Original yup

app.setYupLocale(locale: string | object)

Language setting

// set by string
app.setYupLocale('mars');
 
// set by object
app.setYupLocale({
  number: {
    min: 'too min',
  },
});

ctx.validate(rules: object[, values: object = null [, options: object = null]])

Async validate. In order to allow asynchronous custom validations all (or no) tests are run asynchronously. A consequence of this is that test execution order cannot be guaranteed. ref: yup-doc

  • rules: validate rules
  • values: validate data, default ctx.request.body
  • options: this will override the options in the config.

ctx.validateSync(rules: object[, values: object = null [, options: object = null]])

Sync validate

  • rules: validate rules
  • values: validate data, default ctx.request.body
  • options: this will override the options in the config.

Questions & Suggestions

Please open an issue here.

License

MIT

Package Sidebar

Install

npm i egg-yup

Weekly Downloads

2

Version

0.0.3

License

MIT

Unpacked Size

7.73 kB

Total Files

7

Last publish

Collaborators

  • seekcx