问题
I have a model form defined in my application, and in one of my form fields, I want the users to enter their inputs, but with the first letter of their inputs in capital. If that's not the case, the application should throw an error and prompt the user to re-enter that particular form entry.
Is there an in-built Django form validator for implementing such a restriction?
PS: I am aware of the capitalize() method provided by ModelForm which stores the form field in database with first letter capitalized. However, this won't work for me, since I want to validate the input BEFORE form submission.
回答1:
from django.db import models
from django.core.exceptions import ValidationError
def validate_capitalized(value):
if value != value.capitalize():
raise ValidationError('Invalid (not capitalized) value: %(value)s',
code='invalid',
params={'value': value})
class MyModel(models.Model):
name = models.CharField(max_length=50, validators=[validate_capitalized])
You can customize ValidationError for your needs. Docs: validators, ValidationError.
回答2:
You could use validators on the form or model fields, see the Documentation: Using validators and Writing validators.
Reference a simple callable that does the check and raise an exception.
来源:https://stackoverflow.com/questions/31540221/django-form-validation-for-accepting-strings-with-first-letter-in-caps