如何使Django表单字段只包含字母数字字符 [英] How can I make a Django form field contain only alphanumeric characters
本文介绍了如何使Django表单字段只包含字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个模型
name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=50, unique=True)
用户不应该在两个字段中都不能使用字母数字的任何其他字符。
I want that the user should not be able to use any other characters than alphanumerics in both fields.
有没有办法?
推荐答案
您将使用验证器以限制现场接受的内容。 RegexValidator
会在这里做的诀窍:
You would use a validator to limit what the field accepts. A RegexValidator
would do the trick here:
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
name = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric])
email = models.EmailField(max_length=50, unique=True, validators=[alphanumeric])
请注意, validate_email
验证器将验证您的电子邮件地址; 字母数字
验证器将不允许有效的电子邮件地址。
Note that there already is a validate_email
validator that'll validate email addresses for you; the alphanumeric
validator above will not allow for valid email addresses.
这篇关于如何使Django表单字段只包含字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文