Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对数组校验时有些问题? #8

Open
zgayjjf opened this issue May 22, 2019 · 3 comments
Open

对数组校验时有些问题? #8

zgayjjf opened this issue May 22, 2019 · 3 comments

Comments

@zgayjjf
Copy link

zgayjjf commented May 22, 2019

想对数组类型进行校验,仅需要是个数字数组就好了,好像没办法进行校验。

最小可复现代码如下:

const AJS = require('another-json-schema')

function isArray(arr) {
  return Array.isArray(arr)
}

const schema = AJS('schema', {
  arr: { type: isArray }
})

const result = schema.validate({ arr: [11, 22, 33] })

console.log(result)

/** 
{
  "valid": false,
  "error": {
    "validator": "type",
    "path": "$.arr",
    "actual": 1,
    "expected": {},
    "schema": "schema"
  },
  "result": {
    "arr": [
      1,
      2,
      3
    ]
  }
}
**/

发现 isArray 里面传进来的是数组项(11、22、33),而不是数组本身。
这样无法保证传入的 arr 本身是数组。

是我遗漏了哪里么?

@nswbmw

@zgayjjf zgayjjf changed the title 好像无法对数组进行校验? 对数组校验时有些问题? May 22, 2019
@zgayjjf
Copy link
Author

zgayjjf commented May 22, 2019

另外,一个嵌套的属性、数组属性一定是必须的?
好像没办法让一个嵌套的属性、数组属性可选,必须要填一个空数组、空对象才行

@nswbmw
Copy link
Owner

nswbmw commented May 22, 2019

@zgayjjf 把:

const schema = AJS('schema', {
  arr: { type: isArray }
})

改成:

const schema = AJS('schema', {
  arr: [{ type: 'number' }]
})

后面这种方式有一个 "bug" 是,无法检查数组是否为空,即:

schema.validate({ arr: [] })

空数组也能通过检查。历史遗留的设计问题,你可以看下源码,有兴趣的话可以提个 pr...

@zgayjjf
Copy link
Author

zgayjjf commented May 23, 2019

你说的这种方式是 ok 的,不过就默认 arr 属性是必须的了吧,没办法不传该参数,至少得传个空数组。

这个问题对于对象属性也存在。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants