使用Django序列化程序验证字段输入

huangapple go评论54阅读模式
英文:

Validate field input using django serializer

问题

我有一个Django模型中的字段code
我需要检查输入字符串是否具有以下属性:

  1. 长度应为5个字符
  2. 第1和第2个字符应为字母
  3. 第3和第4个字符应为数字
  4. 第5个字符应为E或N

我有一个如下所示的序列化器,满足第一个条件。

class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)

    class Meta:
        model = MyModel
        fields = '__all__';

如何满足剩余条件?

英文:

I have a field code in my Django model.
I have to check if the input string has the following properties:

  1. Length should be 5 characters
  2. 1st & 2nd characters should be alphabets
  3. 3rd & 4th characters should be numbers
  4. 5th character should be E or N

I have a serializer as shown below which satisfies the first condition.

class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)

    class Meta:
        model = MyModel
        fields = '__all__'

How can I fulfil the remaining conditions?

答案1

得分: 1

以下是翻译好的部分:

"validate_code"函数的名称在序列化器中不是强制的。你可以根据喜好命名它,只要以单词"validate"开头并接受一个值参数。值参数代表正在验证的字段的值。

下面是关于上面使用的正则表达式模式的一些深入信息。

第1和第2个字符应为字母
[A-Za-z]{2} 匹配任意两个字母字符,确保第一个和第二个字符为字母。

第3和第4个字符应为数字
\d{2} 匹配任意两个数字字符,确保第三和第四个字符为数字。

第5个字符应为E或N
[EN] 匹配E或N中的任何一个,确保第五个字符为E或N。

英文:

The remaining conditions can be fulfilled by adding a custom validator and using regex.

import re

class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)

    def validate_code(self, value):
        # check if the code matches the required pattern
        pattern = r'^[A-Za-z]{2}\d{2}[EN]$'
        if not re.match(pattern, value):
            raise serializers.ValidationError('Code does not match required format')

        return value

The name of the function validate_code is not mandatory in the serializer. You can name it whatever you like, as long as it starts with the word "validate" and takes in a value argument. The value argument represents the value of the field being validated.

Here is a bit of in-depth info about the regex pattern used above.

1st & 2nd characters should be alphabets:
[A-Za-z]{2} matches any two alphabetical characters, ensuring that the first and second characters are alphabet

3rd & 4th characters should be numbers:
\d{2} matches any two numeric characters, ensuring that the third and fourth characters are numbers

5th character should be E or N:
[EN] matches either E or N, ensuring that the fifth character is either E or N

huangapple
  • 本文由 发表于 2023年2月18日 13:46:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定