summary refs log tree commit diff
path: root/synapse/config/validators.py
blob: 2faae0cf4a0c3102a457f3897d218a541f71cba0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import re
from typing import Type

from pydantic import BaseModel
from pydantic.fields import ModelField


def string_length_between(lower: int, upper: int):
    def validator(cls: Type[BaseModel], value: str, field: ModelField) -> str:
        print(f"validate {lower=} {upper=} {value=}")
        if lower <= len(value) <= upper:
            print("ok")
            return value
        print("bad")
        raise ValueError(
            f"{field.name} must be between {lower} and {upper} characters long"
        )

    return validator


def string_contains_characters(charset: str):
    def validator(cls: Type[BaseModel], value: str, field: ModelField) -> str:
        pattern = f"^[{charset}]*$"
        if re.match(pattern, value):
            return value
        raise ValueError(
            f"{field.name} must be only contain the characters {charset}"
        )

    return validator