workfloworchestrator / pydantic-forms

Define JSON scheme with pydantic so a frontend can generate forms with pydantic validators
Apache License 2.0
8 stars 0 forks source link

Translate form errors #10

Open acidjunk opened 1 year ago

acidjunk commented 1 year ago

I needed translated (NL/Dutch) FormValidation errors in a frontend and tried to get that working. There is a package pydantic-translations

I am not sure about the best internationalisation project for pydantic; there's also pydantic-i18n

or (https://pypi.org/project/pydantic-errors-messages-translations/)[pydantic-errors-messages-translations]

With pydantic-translations: I managed to get Dutch / NL form validations errors in the frontend, by changing some code in post_form():

# Loop through user inputs and for each input validate and update current state and validation results
while user_inputs:
    user_input = user_inputs.pop(0)
    # Validate
    try:
        form_validated_data = generated_form(**user_input)
    except ValidationError as e:
        from pydantic_translations import Translator
        tr = Translator('nl')
        errors = [tr.translate_error(error) for error in e.errors()]
        raise FormValidationError(e.model.__name__, errors) from e  # type: ignore

This works as a POC: it might be cool to add this as a feature, by adding an optional language parameter in start_form() and post_form().

Investigate:

Mark90 commented 1 year ago

Sounds like a nice feature.

Regarding:

what's a good format for the language parameter: "nl", "NL-nl"?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language

The most common extra information is the country or region variant (like 'en-US' or 'fr-CA')

I'd vote for being thorough and using the "full" locale identifier. We've always been mixing en-US and en-GB spelling, which as you know have subtle differences. We could now actually add both languages and perhaps use some spellcheck linting to make sure we don't mess up again :)

acidjunk commented 1 year ago

I think the full locale is often used when you also want to set localisation stuff like date formats. But I'm ok with the long version: it might be handy

I want to do some further investigation regarding corner cases; consider a date field; it might be nice to handle the date format in a different way for Dutch / English regions.

acidjunk commented 7 months ago

@Mark90 This looks promising -> https://github.com/boardpack/pydantic-i18n

That seems to have a way to acquire all pydantic2 error messages. Will do a POC soon with it.

Mark90 commented 7 months ago

@acidjunk Nice, I'm curious whether it can translate the "constant" part of the error message, so that we can generate static translation files for the pydantic-forms