【问题标题】:how shall i validate json against schema我应该如何根据模式验证 json
【发布时间】:2016-08-10 02:23:00
【问题描述】:

您好,我正在使用 MEAN STACK,我想针对 mongoose 模式验证来自前端的 JSON 密钥。我正在验证值,但我应该如何验证来自客户端的密钥。

var CategorySchema = new Schema({
    name: {
        type: String,
        lowercase: true,
        default: '',
        trim: true,
        unique: [true, 'Category name already exists'],
        required: [true, 'Category Name cannot be blank'],
        minlength: [4, 'Minimum 4 characters required'],
        maxlength: [12, 'Category name cannot be That long']
    },
    parentCategory: {
        type: String,
        lowercase: true,
        default: '',
        trim: true
    },
    description: {
        type: String,
        lowercase: true,
        default: '',
        trim: true,
        required: [true, 'description cannot be blank'],
        minlength: [10, 'Very short description']
    },
    imageUrl: {
        type: String,
        default: '',
        trim: true
    }
});

如果我提供这种格式会怎样

{

  "IMAGEURL": "c:\abc.png",         instead of imageUrl
  "DESCRIPTION": "here is some description", INSTEAD OF description
  "PARENTCATEGORY": "Men Wear", instead of parentcategory
  "Name": "Shirts" instead of name
}

我正在编写将被验证的rest api,是否有必要检查这些东西。请帮忙

【问题讨论】:

  • 我想要对节点中的 json 进行服务器端验证
  • 11 个月后:我想JSON schema 是您要找的东西?

标签: json node.js mongodb validation mongoose


【解决方案1】:

对我来说,json 架构是如此复杂。我建议使用Json Pattern Validator

npm install jpv

使用起来非常简单,不需要任何额外的键,并且有很多模式来描述json。

import jpv from 'jpv';

var json = {
  status : 'OK',
  data : {
    url : 'http://example.com'
  }
}

var pattern = {
  status : /^OK$/,
  data : {
    url : "[url]" 
  }
}

console.log( jpv.validate(json, pattern ) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多