Surendranatha Reddy T
Surendranatha Reddy T

Reputation: 294

How can i validate django field with either of two validators?

Here is the code, I want ip_address to satisfy either of validate_fqdn or validate_ipv4_address.

import re
def validate_fqdn(value):
    
    pattern = re.compile(r'^[a-zA-Z0-9-_]+\.?[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$')
    if not pattern.match(value):
        raise ValidationError('Provided fqdn is not valid')
    return value

class KSerializer(serializers.HyperlinkedModelSerializer):
    ip_address = serializers.CharField(max_length = 100, validators = [validate_fqdn, validate_ipv4_address])

How can I achieve this?

Upvotes: 0

Views: 119

Answers (1)

cafce25
cafce25

Reputation: 27532

A new validator will do:

def validate_fqdn_or_ipv4_address(value):
    try:
        return validate_fqdn(value)
    except:
        return validate_ipv4_address(value)

Upvotes: 1

Related Questions