0.0.0-alpha-0f • Published 7 years ago

schema-json v0.0.0-alpha-0f

Weekly downloads
1
License
ISC
Repository
-
Last release
7 years ago

Check json Schema or format

It's a simple module to check a json schema

Create Json Schema

import {SchemaJson} from 'schema-json';

let schema = new SchemaJson({
    name: String,
    phone: [{
        code:{type:Number, required: true, error: "hello"},
        number: Number
    }],
    address:{
        vill: { type:String, required: true, message: "Custom message"},
        dist: String,
        pin: Number
    }
});

field can be javascript data type Number, String, Object, Boolean and Array

####field options 1. type: Can be jvascript data type Number, String, Object, Boolean and Array. 2. required: Makes a field required. default it is false. 3. message: Sets custom message for field error.

Check data with schema

let result = schema.isValid({
     name: "asdfgh",
     phone: [{
             code: 12345,
             number: 1234567
     }],
     address: {
         vill:"north Raipur p1-1",
         dist: "QWERTYU",
         pin: 123456
     }
    });
console.log(result)  // Result true

##Error handling if callback is provided in isValid(data, callback) then it will be called with two argument err and isValid

import {SchemaJson} from 'schema-json';
let s = new SchemaJson({
    name: String,
    phone: [Number],
    address: String

});

let result = s.isValid({
    name: "asdfgh",
    phone: [123456,"wertyu"],
    address: 23456
}, (err: any, isValid: boolean)=>{
    console.log(err); // {"phone":[{"index":1,"error":{"type":false,"message":"Value is of invalid type"}}],"address":{"type":false,"message":"Value is of invalid type"}}
});

The error will come with the corresponding path

{
  "phone":[
    {
      "index":1,
      "error":{
        "type":false,
        "message":"Value is of invalid type"
      }
    }
  ],
  "address":{
    "type":false,
    "message":"Value is of invalid type"
  }
}