[Answered ]-Validate field input using django serializer

1👍

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

Leave a comment