Zod Form Validator

Another Form Validator

This one uses zod to help with the validation

There are 2 ways to use it

  1. add a FormValidator as a custom component
  2. add a Validator instance to a form that has inputs that need validating

e.g. 1

from anvil_extras import zod as z

user_schema = z.typed_dict({
    "name": z.string(), 
    "email": z.string().email(),
    "age":  z.coerce.integer().ge(18).lt(100)
})

input_schema = {
    "name": lambda: anvil.TextBox(),
    "email": lambda: anvil.TextBox(type="email"),
    "age": lambda: anvil.TextBox(type="number")
}


class Form1(Form1Template):
    def __init__(self, **properties):
        self.validator_1.zod_schema = user_schema
        self.validator_1.input_schema = input_schema

e.g.2

class Form2(Form2Template):
    def __init__(self, **properties):
        self.validator = Validator(self, user_schema)
        # Form2 has inputs and error labels added in the designer
        # it uses the naming convention self.age_input, self.age_error

And that’s it.
When you want to submit the form use the schema to validate the item

def submit_button_click(self, **event_args):
    try:
        # validate the item on the client
        user_schema.parse(self.item)
        # we can also validate the item on the server with the same approach
        anvil.server.call("do_something", self.item)
    except z.ParseError as e:
        ...

Hopefully it makes someone’s life a little easier!

Here’s a clone link:

And if you have questions/comments/suggestions feel free to add an issue/discussion over at the github page:

6 Likes

@stucork

Thank you very much for that!

I am developing a form builder helper using Zod. I’ll put the engine inside of a shareable app!

Take a look at Form Builder using Zod…