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

When coerceTypes is true, custom format function was not executed. #349

Closed
amazing-gao opened this issue Nov 25, 2016 · 2 comments
Closed

Comments

@amazing-gao
Copy link

What version of Ajv are you using? Does the issue happen if you use the latest version?

Ajv options object (see https://github.com/epoberezkin/ajv#options):

{
    removeAdditional: 'all',
    coerceTypes: true,
    allErrors: true
}

JSON Schema (please make it as small as possible to reproduce the issue):

{
    "properties": {
      "id": {
        "type": "integer",
        "format": "int32"
      }
    }
  }

Data (please make it as small as posssible to reproduce the issue):

{
    "id": "1234"
}

Your code (please use options, schema and data as variables):

const Ajv = require('ajv');

function foo() {
  const ajv = new Ajv({
    removeAdditional: 'all',
    coerceTypes: true,
    allErrors: true
  });

  ajv.addFormat('int32', (data)=> {
    data = Number(data);
    console.log('foo int32 ', data)

    if (data <= 2147483647 && data >= -2147483647)
      return true;
    else
      return false;
  });

  const schema = {
    "properties": {
      "id": {
        "type": "integer",
        "format": "int32"
      }
    }
  }

  const data = {
    id: '1234'
  }

  var validate = ajv.compile(schema);
  var ret = validate(data);
  console.log(ret, data, validate.errors);
}

foo();

Validation result, data AFTER validation, error messages:

// console.log output
true { id: 1234 } null

What results did you expect?
valid and int32 format function was executed.
but int32 custom function was not executed.

Are you going to resolve the issue?
At this moment, I don't know how to resolve it.

@epoberezkin
Copy link
Member

At the moment, formats only apply to strings, not to any other data type.
Coercion happens when the type is checked, before applying any other keywords, so the data becomes a number and format keyword is not applied.
There is a feature #291 to support format for all datatypes that I agreed to include - @nimerritt was going to create a PR - are you still?

@nimerritt
Copy link
Contributor

@epoberezkin Yes, I mostly finished it last weekend but need to figure out how to support type detection in the format-rule, when there is no type declaration. I'll push what I have tomorrow and may need to tag you for a tip if I can't figure it out.

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

No branches or pull requests

3 participants