Skip to content

Validators

Krzysztof Czarnecki edited this page Dec 15, 2021 · 3 revisions

Validators

Creating your own validators

It is possible to quickly write your own validators. You need to create a function with a signature that matches mkcommit.model.ValidatorClosure, so a function that returns another function, where the inner function accepts a string and returns a boolean. Quick example:

from mkcommit.model import Validator
import re


def matches(pattern: str) -> Validator:
    def _v(msg: str) -> bool:
        if re.match(pattern, msg):
            return True
        else:
            return False
    _v.__doc__ = f"The pattern {pattern} hasn't been matched to the input"
    return _v

The above is the implementation of the matches validator.

You can declare validators directly within your *.mkcommit.py file or import them from somewhere else.

Built-in validators

  • matches(pattern) - matches an arbitrary RegEx pattern
  • is_int - succeeds only if the input is a valid integer
  • is_float - succeeds only if the input is a valid float
  • min_len(ln) - succeeds only if the input is at least ln characters long
  • max_len(ln) - succeeds only if the input does not exceed ln
  • validate_initials(letters_f, letters_l) - opinionated validator for human initials, succeeds only if the input consists of a set of letters_f number of first name letters and letters_l number of last name letters. Additionally the first letter of both the first name and last name must be capitalized, e.g. validate_initials(2,2) will succeed with inputs KrCz and AbCd but not KrzCza or AbcDe.
  • is_true - succeeds if input was provided or a yes/no question was answered with a y
  • is_false - succeeds if input was not provided or a yes/no question was answered with an n
  • are_keywords_selected - a descriptive alias for min_len(1) that is used with e.g. semantic suite's ask_keyword
Clone this wiki locally