简体   繁体   中英

validate Property through object?

How do I validate the property through object? I have define the list of Property in the checkProperty

I expected missingFields to return Batch.Name is missing.

Currently is is outputting [ 'Batch.Id', 'Batch.Name' ] which is wrong.

 let data = { Batch: { Id: 123, }, Total: 100, } let checkProperty = ['Total', 'Batch.Id', 'Batch.Name']; let missingFields = []; checkProperty.forEach(field => { if (!data[field]) { missingFields.push(field); } }); console.log(missingFields); 

You'll have to use something like reduce after splitting on dots to check whether the nested value exists:

 let data = { Batch: { Id: 123, }, Total: 100, } let checkProperty = ['Total', 'Batch.Id', 'Batch.Name']; let missingFields = []; checkProperty.forEach(field => { const val = field.split('.').reduce((a, prop) => !a ? null : a[prop], data); if (!val) { missingFields.push(field); } }); console.log(missingFields); 

You can use this

The reason why this data[field] when do data[Batch.Id] it tries to check at the first level key of object. in our case we don't have any key such as it tries to check at the first level key of object. in our case we don't have any key such as Batch.Id .

For our case we need `data[Batch][Id]` something like this which first searches 
 for `Batch` property and than or the found value it searches for `Id`.

 let data = { Batch: { Id: 123, }, Total: 100, } let checkProperty = ['Total', 'Batch.Id', 'Batch.Name']; let missingFields = []; checkProperty.forEach(field => { let temp = field.split('.').reduce((o,e)=> { return o[e] || data[e] },{}); if (!temp) { missingFields.push(field); } }); console.log(missingFields); 

If you can use additional libraries Ajv is perfect for this. Instead of creating all the logic by yourself, you can create a schema and validate it.

var schema = {
  "type": "object",
  "properties": {
    "Batch": { 
        "type": "object", 
        "required": ["Id", "Name"],
        "properties": 
        {
        "Id":{},
        "Name":{},
        },
       },
    "Total": {}
  }
};


let json = {
  Batch: {
    Id: 123,
  },
  Total: 100,
}

var ajv = new Ajv({
    removeAdditional: 'all',
    allErrors: true
});

var validate = ajv.compile(schema);
var result = validate(json);
console.log('Result: ', result);
console.log('Errors: ', validate.errors);

Returns the following error message:

dataPath:".Batch"
keyword:"required"
message:"should have required property 'Name'"
params:{missingProperty: "Name"}
schemaPath:"#/properties/Batch/required"

https://jsfiddle.net/95m7z4tw/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM