I'll-Be-Back
I'll-Be-Back

Reputation: 10828

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);

Upvotes: 3

Views: 93

Answers (3)

Rashomon
Rashomon

Reputation: 6762

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/

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37745

You can use this

The reason why thisdata[field]when dodata[Batch.Id]it tries to check at the first level key of object. in our case we don't have any key such asBatch.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);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370979

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);

Upvotes: 3

Related Questions