我该如何验证json对模式

时间:2016-04-18 11:17:10

标签: json node.js mongodb validation mongoose

嗨,我正在使用MEAN STACK,我想验证来自前端的JSON密钥与mongoose模式。我正在验证值,但我如何验证来自客户端的密钥,例如。

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是否有必要检查这些内容。请帮助

1 个答案:

答案 0 :(得分:0)

对我来说,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 ) )