adonisjs / core

AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.
https://adonisjs.com
MIT License
16.92k stars 640 forks source link

string validator does not return empty string when schema.string.nullableAndOptional() is used #4127

Closed mtariqsajid closed 1 year ago

mtariqsajid commented 1 year ago

Prerequisites

Node.js and npm version

node: 18.15.0 npm: 9.5.0

Sample Code (to reproduce the issue)

import { schema, CustomMessages } from '@ioc:Adonis/Core/Validator'
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class UserValidator {
  constructor(protected ctx: HttpContextContract) { }

  public schema = schema.create({
    id: schema.number(),
    name: schema.string.optional(),
    description: schema.string.nullableAndOptional(),
  })
}

when this validator invoke it does not return the field description if its empty pass from the request. I want to validator to return empty string so i can update the user description field as empty string

mtariqsajid commented 1 year ago

anyone please respond @shreeve @allanfreitas @yann-yinn @mul14

McSneaky commented 1 year ago

So basically. You want there to be default values and in current case default value should be empty string?

I don't think validator supports default values, but you can add them manually after validation

const validated = await request.validate(UserValidator)
// If description isn't set, then give it default value
if (!validated.description) {
  validated.description = 'Foo bar and baz'
}
mtariqsajid commented 1 year ago

So basically. You want there to be default values and in current case default value should be empty string?

I don't think validator supports default values, but you can add them manually after validation

const validated = await request.validate(UserValidator)
// If description isn't set, then give it default value
if (!validated.description) {
  validated.description = 'Foo bar and baz'
}

but this will become cumbersome, is their way to handle this if i have a lot of fields in model. and i might accidentally forgot about some model fields. how to keep it sync with model ? any suggestions . @McSneaky

thetutlage commented 1 year ago

If the user description is empty, then it must be represented as null in the database and not an empty string (for the sake of normalized data).

Therefore, I recommend marking the description column in your case as nullable and set the value to null.