kristianmandrup / schema-to-yup

Schema to Yup validation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

handling trailing and leading spaces, `trim` doesn't work ?

vaheqelyan opened this issue · comments

commented

Is there a way to trim a string property right before validation?
I need space/tab strings to be considered as empty strings
I know there is no trim in jsonschema, but anyway, is there any way to make this work?

const schema = {
  type: 'object',
  required: ['name', 'description', 'itemType'],
  properties: {
    name: {
      type: 'string',
      trim: true
    }
}

buildYup(schema)

Thanks!

Just fixed it by adding trim to the typeEnabled method of String type handler

  get typeEnabled() {
    return [
      "normalize",
      "trim",
      "minLength",
      "maxLength",
      "pattern",
      "lowercase",
      "uppercase",
      "email",
      "url",
      "genericFormat",
    ];
  }

Now the trim test passes (see test folder)

import { createStr, createSchema } from "./_helpers";

describe("trim - strict", () => {
  const conf = { trim: true, strict: true, key: "name" };
  describe("create schema", () => {
    test("trim", () => {
      expect(createStr(conf)).toBeTruthy();
    });
  });

  describe("validate", () => {
    const entry = createStr(conf);
    const schema = createSchema(entry, "name");

    test("valid name - trimmed", () => {
      const valid = schema.isValidSync({
        name: "abc"
      });
      expect(valid).toBeTruthy();
    });

    
    test("invalid name - not trimmed", () => {
      const valid = schema.isValidSync({
        name: "   zxy124 "
      });
      expect(valid).toBeFalsy();
    });
  });
});

Perhaps try combining it with a regex validator instead of strict: true