Categories
Mastering Development

Can I build a serializer that validates username and email existence on is_valid call?

guys!
I have this serializer class for the user model

class UserSerializer(serializers.ModelSerializer):
    username = serializers.RegexField("^(?=.{6,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$")
    full_name = serializers.RegexField("^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)")
    email = serializers.EmailField()
    phone = serializers.RegexField("^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$")

    class Meta:
        model = User
        fields = ['username', 'full_name', 'email', 'password', 'phone']

This is my serializer class for the moment. I want to validate that the username and email does not exist before saving an user. Can I do it without manually writing the validations? And I also need to validate the regex for the username and the email field for the email

Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *