Skip to content

Support for adding validator decorator #464

@sarangsbabu367

Description

@sarangsbabu367

Is your feature request related to a problem? Please describe.
pydantic supports the provision to add a validator decorator for fields. Is there anyway to represent this in jsonschema and data-model-generator will generate this. This can be treated as a custom-path where decorator code will be present in the given path and during the model generation this method needs to be attached to the model(Not sure about this).

Describe the solution you'd like

  • Support for specifying validator in jsonschema.
  • Need a provision to specify validators in the jsonschema and data-model generator should recognize this.
from pydantic import BaseModel, ValidationError, validator

class UserModel(BaseModel):
    name: str

    @validator('name', pre=True)
    def name_must_contain_space(cls, v):
        if ' ' not in v:
            raise ValueError('must contain a space')
        return v.title()
  • validator name and args can be described in jsonschema and path to the code can be made custom, since it will contain other logic.
type: object
properties:
  name:
    type: string
    x-validator:
      type: object
      properties:
        name:
          const: name_must_contain_space
        path:
          const: a.b.c._name_must_contain_space
        args:
          pre:
            const: True
  • With the above representation the validator logic can be declared in another method and a simple reference needs to be added in model. Like,
from pydantic import BaseModel, ValidationError, validator
from a.b.c import _name_must_contain_space

class UserModel(BaseModel):
    name: str

    @validator('name', pre=True)
    def name_must_contain_space(cls, v, values, **kwargs):
        return _name_must_contain_space(cls, v, values, **kwargs)

Describe alternatives you've considered

  • For implementing this behaviour, generated models needs to be extended and need to add this validator method in the extended model.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions