Django: Form validation for accepting strings with first letter in CAPS

江枫思渺然 提交于 2021-01-28 08:13:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!