Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for transform #173

Open
tkamstra opened this issue Aug 30, 2024 · 1 comment
Open

Support for transform #173

tkamstra opened this issue Aug 30, 2024 · 1 comment

Comments

@tkamstra
Copy link

tkamstra commented Aug 30, 2024

It is known in Yup that type number has weird requirements when validating a number input that is blank. A common fix is to add the following code: .transform = (_, val) => (val !== '' ? Number(val) : null)

Is there any way to add transform support?

edit:
tried adding a typeHandler, but no avail
image
image

@tonthon
Copy link

tonthon commented Sep 11, 2024

I did it this way :

import {YupNumber, createNumberGuard} from 'schema-to-yup/src/types/number/index.js'

import  * as Yup from 'yup'

class MyCustomNumberHandler extends YupNumber {
  get validatorInstance(){
    let result = this.validator.number()
    const nullable = this.value.nullable === true || this.value.null === true;
    if (nullable){
      result = result.transform(
        (value, originalValue) => (
          ['', undefined, false, NaN, null].includes(originalValue)
          ? null
          : Number(String(originalValue).replace(/,/g, '.'))
        )
      )
    }
  }
  static create(obj){
    return new MyCustomNumberHandler(obj);
  }
  static schemaEntryFor(obj) {
    return MyCustomNumberHandler.create(obj).createSchemaEntry();
  }
}

const defaultConfig = {
  logging: false,
  enable: { log: true, warn: true, error: true },
  typeHandlers: {
    number: (obj, config={}) =>  createNumberGuard(obj, config).verify() && MyCustomNumberHandler.create(obj).createSchemaEntry()
  }
}

Edit : Added to support for initial null values
Edit 2 : Added call to NumberGuard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants