acornejo/jjv

Is there support for validating one property of a model?

Closed this issue · 3 comments

I'm not sure if I just missed it in the docs, but is there a way to validate just one property at a time? My use case is I want to be able to validate individual properties in the browser to be able to provide immediate feedback to a user when they enter an invalid value in a text box. Anyone have discussions on this sort of feature in the past?

An example of what I'm envisioning, based on the example in the README.md

// given a defined schema for a user
env.addSchema('user', {
    type: 'object',
    properties: {
        firstname: {
            type: 'string',
            minLength: 2,
            maxLength: 15
        },
        lastname: {
            type: 'string',
            minLength: 2,
            maxLength: 25
        },
        gender: {
            type: 'string',
            enum: ['male', 'female']
        },
        email: {
            type: 'string',
            format: 'email'
        },
        password: {
            type: 'string',
            minLength: 8
        }
    },
    required: ['firstname', 'lastname', 'email', 'password']
});

// and given a user model
var userModel = {
    firstName: 'Derek',
    middleName: 'Jon',
    lastName: 'Pavao',
    gender: 'male',
    email: '',
    password: 'foobar'
};

// I'd like to be able to just validate the email property of the userModel. I'm thinking of two different syntax.

// The first syntax could be something like ...
var errors = env.validate('user.email', userModel);

// or the following syntax ...
var errors = env.validate('user', 'email', userModel);

If this is something people think could be useful, I'd be very interested in trying to put together a PR for this feature.

I believe this is already supported, since JJV fully supports json pointers.

I am a bit rusty on the syntax, so I recommend you read the documentation on the spec on json-schema.org. I believe the syntax is something like:

env.validate('user#/properties/email', userModel.email);

However, given that validation is SO fast, I would personally not even bother with this. Just validate the entire object, you can filter the errors by field quite easily and only display the ones that you care about.

given the lack of reply, I am closing this as solved. If this is not the case please reopen.

Sorry, yeah. That above example will work for my purposes. Thanks.