adonisjs / validator

Schema based validator for AdonisJS
MIT License
116 stars 39 forks source link

Add support for nullable values #128

Closed stropitek closed 2 years ago

stropitek commented 2 years ago

Why this feature is required (specific use-cases will be appreciated)?

It is often needed to create an api which allows to unset values explicitely in a backend.

Since undefined is not serializable to JSON, we need to pass null to indicate that intent.

Currently, @adonisjs/validator does not have strong support for nullable fields. If a required field is null, validation fails, and if an optional field is null, validation will pass, but the property which was null will be stripped away from the validated result.

for example:

export default class DataValidator {
  public schema = schema.create({
    field: schema.number.optional(),
  });
}

// When passed {field: null} the validation result will be an empty object {}

I want null to be passed to the validated result because I need to pass it to lucid (using a model's merge method) to explicitely unset a nullable field. If the field is undefined, then the merge method will leave the column untouched in the database.

Have you tried any other work arounds?

I could always add some custom logic to controllers to add the missing null values before passing them to lucid, but that would blur separation of concern and complicate the code.

Are you willing to work on it with little guidance?

Yes

thetutlage commented 2 years ago

Fixed in https://github.com/adonisjs/validator/commit/c9a0e3aa4652014c6079bbd37b05e91b307ba590. Release + docs will be out during this week