oussamahamdaoui/forgJs

allowed fields

Closed this issue · 9 comments

this package is awesome. thnk you!

suggestion for the functionality extands.

it will be very usefull to check required and allowed keys in anobject

Can you explain please 😕
All fealds are required by default, if you need optional feeld you have to use optional in your rules
Thanks for your help

oh, I thougth I made my answer...
I will try again

I got it didn't see that you have changed the title its clear now
Do you have an idea on how that is going to work?

it's true, my explanations weren't clear enough
let see this example:

const v = new Validator({
    firstName: new Rule({ type: 'string' }),
    lastName: new Rule({ type: 'string' }),
    age: new Rule({ type: 'int', optional: true }),
 });

v.test({
    firstName: 'John',
    lastName: 'Smith',
    kekeke: [1,2,3,4,5],
});

it will be valid,
but then I will dynamicly generate mysql query,
and I will get a message, that there is no "kekeke" field in some table

so I want to be able to set allowed fields

I undestood that partm but i dont a nice sintax for that? Do you have any suggestions

well may be something like:

v.test({
    firstName: 'John',
    lastName: 'Smith',
}, true);

that looks good, thats a good idea, ill try to implement this.

if it's interesting for you, here is my allowed fields validation implementation:

import { Validator, Rule } from '@cesium133/forgjs';

export class MyValidator {

    private _validator;
    private _res;
    private _next;
    private _allowedFields;

    constructor(rules, res, next) {
        this._validator = new Validator(rules);
        this._res = res;
        this._next = next;
        this._allowedFields = [
            ...Object.keys(rules),
            'page',
            'itemsPerPage',
            'date_from',
            'date_to',
            'days_count',
        ];
    }

    public check(data) {
        const errors = this._validator.getErrors(data);

        for (const field in data) {
            if ( !this._allowedFields.includes(field) ) {
                errors.push(`'${ field }' field is not allowed`);
            }
        }

        if (errors.length) {
            this._res.status(449).send({errors});
            return;
        }

        this._next();
    }
}

Hey, sorry for the wait i ended up making all fildes present in the validator requred so if there is a field thats not in the rulle the return will be false.
I also updated the npm version
Hope this helps