Solvedajv Custom coerce types/functions

Would be great to be able to do something like:
{ "date": { "format": "date", "coerce": function(value){ return moment(value,'DD/MM/YYYY') } } }

There would be infinite possibilities and usage cases.

Anyway, thanks - great module!

20 Answers

βœ”οΈAccepted Answer

Maybe example would help in docs, but the idea here is explained in docs you mention - the validation function in all keyword types but "macro" (i.e. "validate", "compile" and "inline") receives "parent data object" and "the property name in the parent data object" as parameters. That allows custom keywords to modify the data being validated in any way they want, e.g.

const collectionFormat = {
  csv: (data, dataPath, parentData, parentDataProperty, rootData) => {
    var arr = [];
    // process data to populate array
    if (success) parentData[parentDataProperty] = arr;
    return success; // true or false - validation result
  },
  // ... other list types
};

ajv.addKeyword('collectionFormat', {
  type: 'string',
  compile: (schema) => collectionFormat[schema],
  metaSchema: {
    enum: ['csv' /* , ... */]
  }
});

The only caveat at the moment is that custom keywords will be validated AFTER standard keywords in the same schema object, so if you expect to define validation rules for the CHANGED data these rules cannot be in the same object, they should be in the next subschema of "allOf" keyword:

{
  allOf: [
    {
      // modify data
      collectionFormat: 'csv'
    },
    {
      //validate data
      type: 'array'
      // etc.
    }
  ]
}

I thought several times about allowing to define custom keywords that execute BEFORE standard, but I decided against it because it implies the need to manage order implicitly and there is no way of telling the execution order by looking at the schema. I think it is better that in cases the order matters you MUST use allOf keyword, otherwise the keywords should be independent of execution order.

What may make sense though is to add some extra requirement to the keyword definition that it MUST NOT be used in the same schema with other validation keywords to enforce that it is used in its own schema object, which can be useful in cases like above.

In any case, at the moment it is something you just have to remember.

Related Issues:

18
ajv npm ERR! peer dep missing: ajv@^6.0.0, required by ajv-keywords@3.1.0
This is fixed by adding ajv in your project The problem is almost certainly with npm itself. ...
17
ajv Custom Error Messages
πŸ‘ This feature would be very interesting to me too bad it isn't handled in ajv.. As amcdnl said ...
13
ajv missing file
Other solution is to add a manual resolution in the package.json: then you can use both yarn or npm ...
11
ajv NPM: 6.9.0 AJV Commit causing failure to execute node_modules (multiple dependencies affected i.e. ESLint and WebPack Loaders)
Add to your package.json will create a work around (I am using yarn don't know if it will work for n...
3
ajv Custom coerce types/functions
Maybe example would help in docs but the idea here is explained in docs you mention - the validation...
96
fastapi WARNING: Unsupported upgrade request.
This error is not part of the FastAPI codebase When attempting to run this (using UviCorn) it starts...
64
fastapi [QUESTION] How to bridge Pydantic models with SQLAlchemy?
I just finished integrating Pydantic ORM mode into FastAPI it is released as version 0.30.0 πŸŽ‰ The n...
52
fastapi [QUESTION] How to send 204 response?
Instead of returning None and instead of injecting the response just return a newly created response...
43
pydantic Automatic conversion from float to int?
You got a misfeature there buddy Automatic conversion (by default!) from float to int is a terrible ...
42
fastapi OpenAPI UI not working properly when using automatic swagger-ui CDN (swagger-ui-3.30.1)
Thanks for reporting it and for all the discussion here everyone! πŸš€ β˜• Indeed it's a bug in Swagger ...
34
react jsonschema form Should we move to Bootstrap v4?
IMO we should get rid of Bootstrap to be fully agnostic Maybe we can still support frameworks by cre...
34
fastapi [QUESTION] Is this the correct way to save an uploaded file ?
@classywhetten FastAPI has almost no custom logic related to UploadFile -- most of it is coming from...
34
fastapi [QUESTION] Storing object instances in the app context
@ebarlas you're 100% right Description In Flask ...
32
pydantic How to have an β€œoptional” field but if present required to conform to non None value?
This is irking me at the moment Passing in a field as None is fundamentally different from not passi...
30
fastapi [QUESTION] aiohttp integration best practice
That is one way if you want create a new session for every request You can also use a singleton appr...
29
json schema spec v6 annotation: named enumerations
My first reaction was that's a cumbersome mess and then I wrote it out and now I agree with you :-) ...
28
pydantic Class attributes starting with underscore do not support assignment
Hello there I use pydantic in FastAPI as well and I use mongodb as database Bug For bugs/questions: ...
26
fastapi logs with FastAPI and Uvicorn
Doing : is exactly what I was looking for ! Thank you dbanty. Hello Thanks for FastAPI easy to use i...
24
pydantic mypy: invalid type comment or annotation
The above is not quite right as well because the first parameter to Field is the default value In th...
23
pydantic [Feature Request] Provide a discriminated union type (OpenAPI 3)
So Usage would be something like Feature Request Pydantic currently has a decent support for union t...
22
fastapi [QUESTION] Client Credentials Flow openAPI UI
I think I found the solution for others looking to implement the code - tiangolo has already enabled...
21
fastapi FastAPI 0.65.2 POST request fails with "value is not a valid dict" when using the Requests library; 0.65.1 works (with a caveat)
Can confirm this still happens! We solved it by adding a -H Content-Type: application/json to the cu...
19
fastapi [QUESTION] Using pydantic models for GET request query params? Currently not possible, have to use dataclasses or normal classes.
@LasseGravesen You would do it like this: Check the docs here: https://fastapi.tiangolo.com/tutorial...
18
jsonschema Package version mechanism incompatible with AWS Lambda
@Julian Perhaps a blurb can be added to the docs related to deploying this library using Serverless?...
18
react jsonschema form Validate onBlur?
Why was this closed? This should be kept open and a prop should be added to the <Form> so that this ...
18
fastapi [QUESTION] about threads issue with fastapi.
Hello Hi I have a question about the threads issue with fastapi ...
15
pydantic add exclude to Config
Hi Folks Thank you very much for supporting the config model exclude feature in 1.9.! This is going ...
15
fastapi [FEATURE] support for rate-limit
I've taken a stab at adapting flask-limiter to starlette and FastAPI Is your feature request related...
14
fastapi [QUESTION] How can I serve static files (html, js) easily?
Hi in case a solution is still needed though the issue is closed Description How can I serve static ...
14
fastapi Using UploadFile and Pydantic model in one request
Oups sorry I forgot I made custom validator to transform str to json for Model: ...
13
fastapi How can I pass the configuration in the app?
Is the example I posted above not clear enough? Without going into all the nuances of everything my ...
12
fastapi [BUG] openapi.json fails to be generated for nested models
oups sorry I think your mistake is putting response_model=SimilarProducts in the wrong spot it's in ...
11
react jsonschema form Allow the insertion of errors from outside JSONSchema validation
As an alternative solution It's great to be able to define a regex to validate an input however that...
11
fastapi Debug Logging (Maybe just a n00b issue)
ok so basically I'm using this in a applog package you use it wherever your entrypint is this way sh...
11
fastapi [QUESTION] How ot handle generic text.plain POST requests
@CockyAmoeba tl;dr: Body(...) means a body parameter that is required The first argument to Body For...
11
fastapi [QUESTION] Use UploadFile in Pydantic model
Thanks a lot for your helpful comment So I guess I'd have to explicitly separate the file from the J...
11
fastapi [BUG] Use third party class as property in pydantic schema
I'm using the solution proposed by @tiangolo up above just I preferred doing this: this way I can ei...
10
ngx formly Is it somehow possible to eliminate <formly-field>?
The new behavior will act like <router-outlet></router-outlet> the content will be rendered right af...
9
pydantic Pydantic equivalent of Marshmallow Context-aware serialization
I found this working and clear solution for me :) Models should inherit this modified BaseModel: In ...
5
ngx formly how-to use ngx-formly with ngx-translate
You can use one of the following methods: expressionProperties https://stackblitz.com/edit/ngx-forml...
5
fastapi [FEATURE] Inheritance and Polymorphism support
I think real inheritance and polymorphism support would be very useful Actually ...
4
pydantic Re-use validators?
The issue was closed by #941 but allow_reuse seems not to have been documented yet If anyone is inte...
4
fastapi [FEATURE] msgpack response if client asks for application/x-msgpack
@sandys this is kind of a hacky integration but except from the direct mspack packing / unpacking pa...
65
vee validate "Unexpected token export" when importing validation rules with Jest
Same as @zadigus above Versions vee-validate: 3.0.4 vue: 2.6.10 Describe the bug I've seen that this...
52
validator.js Why I can't configure isAlpha or isAlphanumeric to also include spaces?
i subscribe to the isAlpha(str { allow_spaces: true }) idea What's the reason for not being able to ...
47
vee validate Vee-Validate locale change from EN to NL not working
It works for me on version ^2.1.0-beta.6 Versions: VueJs: 2.1.10 Vee-Validate: 2.0.0-beta.25 Descrip...
41
vee validate Reset form validation
Check the available methods on the errors bag object you can use clear or remove to remove any error...
19
express validator Schema with isIn validation
Try options: [['one' 'two' 'zero']] The options array is for passing each param Since isIn() expects...
18
vee validate VeeValidate v3.0 πŸš€
@victor-ponamariov > my workaround to implement it: Regex from Zemljoradnik VeeValidate 3.0 This is ...
17
vee validate Clear errors after form submition
Hey I was having issues with clearing form inputs and resetting the errors much like a few here ...