JavaScript数据验证器

JavaScript data validator?

本文关键字:验证 数据 JavaScript      更新时间:2023-09-26

寻找可以验证输入的库,例如:

{ points: array of { x: positive and < 20, y: positive and < 15 } }

最好同时在服务器端和客户端工作,并返回布尔值或抛出异常。

我明确不需要的是字符串或表单验证,我只是想检查客户端发送的JSON是否可以安全处理,而不需要大量的分散检查。

你也可以试试Skematic

数据结构和规则验证引擎。JS对象的健壮模式。

它允许您设计数据模型,然后根据这些模型格式化和验证数据。

适用于浏览器(Skematic全局)或Node/io.js。

要解决您的请求,像这样的基本内容应该可以工作:

// -- Define a simple data structure
var YourData = {
  points: {
    type:'array', 
    default: [],
    schema: {
      x: { type: 'number', required: true, rules: { min:0, max:20 } },
      y: { type: 'number', required: true, rules: { min:0, max:15 } }
    }
  }
};
// -- Validate an object
Skematic.validate( YourData, {points:[ {x:-1,y:10} ]} );
// {valid:false, 
//  errors:{
//    points: {0:{x:['Failed: min']}}
// }}

没关系,我自己写的

  • https://bitbucket.org/virtulis/validata/overview
  • https://www.npmjs.org/package/validata