validators: Add check_int_in validator.

This is a useful helper for our enum format fields where we want to
only allow a fixed list of integer values.
This commit is contained in:
Matheus Melo
2019-11-16 13:38:27 -03:00
committed by Tim Abbott
parent 31558cb8b9
commit 678c3a89d0
2 changed files with 18 additions and 2 deletions

View File

@@ -30,7 +30,7 @@ import ujson
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, URLValidator
from typing import Iterable, Optional, Tuple, cast
from typing import Iterable, Optional, Tuple, cast, List
from datetime import datetime
from zerver.lib.request import JsonableError
@@ -92,6 +92,17 @@ def check_int(var_name: str, val: object) -> Optional[str]:
return _('%s is not an integer') % (var_name,)
return None
def check_int_in(possible_values: List[int]) -> Validator:
def validator(var_name: str, val: object) -> Optional[str]:
not_int = check_int(var_name, val)
if not_int is not None:
return not_int
if val not in possible_values:
return _("Invalid %s") % (var_name,)
return None
return validator
def check_float(var_name: str, val: object) -> Optional[str]:
if not isinstance(val, float):
return _('%s is not a float') % (var_name,)