快速上手

安装

使用 npm

推荐使用 npm 或 yarn 的方式进行开发,不仅可在开发环境轻松调试,也可放心地在生产环境打包部署使用,享受整个生态圈和工具链带来的诸多好处。

$ npm install racoon-js --save

使用 yarn

$ yarn add racoon-js

使用 CDN

<script src="//cdn.jsdelivr.net/npm/racoon-js@latest/dist/racoon.min.js"></script>

示例

import racoon from 'racoon-js';

// Define data format schema
const schema = racoon.object({
  name: racoon
    .string()
    .min(3)
    .error('name is too short') // You can add your custom error message
    .max(30)
    .error('name is too long')
    .required(), // Name can not be `undefined` or `null`
  age: racoon
    .number()
    .int()
    .default(1) // If value is `null` or `undefined`, then return default value `false`
  married: racoon.boolean(),
  favorite: racoon.object({ // You can define deep nested object format schema
    sports: racoon.array(
      racoon.string().min(1).max(100).required()
    ),
    book: racoon.object({
      title: racoon.string().required(),
      date: racoon
        .string()
        .pattern(/^\d{4}-\d{1,2}-\d{1,2}$/)
        .format((date) => { // Format the return value
          return `${date} 12:00:00`;
        })
    })
  })
});

try {
  const result = schema.validate({
    name: 'Jack',
    age: 22,
    favorite: {
      sports: ['football', 'basketball'],
      book: {
        title: 12,
        date: '2010-1-1'
      }
    }
  });
} catch (error) {
  console.error(error);
  // Error: "favorite.book.title": value should be typeof string
  // ↑↑↑ The error message can be customed
}

// If you don't like `try-catch` code style
// you can use `validateSilent` method
// If validate fail
// then `error` is not emtpy
// otherwise,`error` is `undefined`
// For Example:
const { error, value } = schema.validateSilent({ ... });

最后更新于