model charfield validators

Date: May 10th 2016
Last updated: May 10th 2016

Model validators (also called form validators) check that a model field contains an appropriate pattern before a form can be submitted. I was looking for a way to make sure that a form was submitted using a pattern like 6'6" or 18 5/8". I was able to get this done using RegexValidator.

Useful resources

validators.py (new file in app directory)

from django.core.validators import RegexValidator

board_length_validator = RegexValidator(r'^[0-9+]\'[0-9+]\"$',
                             message='Enter a valid board length e.g. 6\'6\"',
                             code='Invalid name')

models.py

from .validators import board_length_validator

class Board(models.Model):
    # <- snipped ->
    boardlength = models.CharField('Length', 
                                    # add model validator here!
                                    validators=[board_length_validator], 
                                    max_length=6, 
                                    null=True, 
                                    blank=True)
    # <- snipped ->

results matching ""

    No results matching ""