Custom validations for serializer fields Django Rest Framework

from datetime import date
from rest_framework import serializers
def age_restriction(dob):
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
if (not(20 < age < 30)):
raise serializers.ValidationError("You are no eligible for the job")
return dob
class EligibilitySerializer(serializers.Serializer):
email = serializers.EmailField()
name = serializers.CharField(max_length=200)
date_of_birth = serializers.DateField(validators=[age_restriction])
from datetime import date
from rest_framework import serializers
class EligibilitySerializer(serializers.Serializer):
email = serializers.EmailField()
name = serializers.CharField(max_length=200)
date_of_birth = serializers.DateField()
def validate_date_of_birth(self, dob):
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
if (not(20 < age < 30)):
raise serializers.ValidationError("You are no eligible for the job")
return dob
# testing with valid data
data = {
'date_of_birth': '1993-04-08',
'email': 'user@gmail.com',
'name': 'user'
}
s = EligibilitySerializer(data=data)
print(s.is_valid())
# Output: True
print(s.data)
# Output: ReturnDict([('email', 'user@gmail.com'),
# ('name', 'user'),
# ('date_of_birth', '1993-14-08')])
# testing with invalid data
data = {
'date_of_birth': '1980-04-08',
'email': 'user@gmail.com',
'name': 'user'
}
print(s.is_valid())
# Output: False
print(s.errors)
# Output: ReturnDict([('date_of_birth', ['You are no eligible for the job'])])

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store