Is it possibile in DRF to write object based validation and field based validation in the same serializer?

Viewed 32

Is it possible to write a serializer like this?

class CustomUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField()
    password = serializers.CharField()

    def validate(self, data):
        if data['password'] != data['password_confirmation']:
            raise serializers.ValidationError("Passwords doesen't match")
        return data

    def validate_password(self, value):
        if (len(value) < 8):
            raise serializers.ValidationError("Password must be at least 8 characters")
        return value

    def validate_email(self, value):
        lower_email = value.lower()
        if CustomUser.objects.filter(email__iexact=lower_email).exists():
            raise serializers.ValidationError("This email already exists in our database")
        return lower_email
    class Meta:
        model = CustomUser
        fields = ['id', 'email', 'uid'] * uid firebase localId

It is calling the validate_email and validate_password but it's not calling the validate method. In the view i'm calling the is_valid() method. I'm wondering if it's possible to use both of these validations.

0 Answers
Related