def validate(self, data): # Format and validate Postal Code if all( data.get(key) is not None for key in ["country_code", "postal_code"]): postal_code = data["postal_code"] country_code = data["country_code"] if country_code == units.Country.CA.name: formatted = "".join([ c for c in postal_code.split() if c not in ["-", "_"] ]).upper() if not re.match(r"^([A-Za-z]\d[A-Za-z][-]?\d[A-Za-z]\d)", formatted): raise serializers.ValidationError({ "postal_code": "The Canadian postal code must match Z9Z9Z9" }) elif country_code == units.Country.US.name: formatted = "".join(postal_code.split()) if not re.match(r"^\d{5}(-\d{4})?$", formatted): raise serializers.ValidationError({ "postal_code": "The American postal code must match 9999 or 99999" }) else: formatted = postal_code data.update({**data, "postal_code": formatted}) # Format and validate Phone Number if all( data.get(key) is not None and data.get(key) != "" for key in ["country_code", "phone_number"]): phone_number = data["phone_number"] country_code = data["country_code"] try: formatted = phonenumbers.parse(phone_number, country_code) data.update({ **data, "phone_number": phonenumbers.format_number( formatted, phonenumbers.PhoneNumberFormat.INTERNATIONAL), }) except Exception as e: logger.warning(e) raise serializers.ValidationError( {"postal_code": "Invalid phone number format"}) return data
def valid_datetime_format(value): try: datetime.strptime(value, "%Y-%m-%d") except Exception: raise serializers.ValidationError( "The datetime format must match YYYY-MM-DD HH:HM")
def validate(self, data): validated_data = super(PickupRequest, self).validate(data) if (len(validated_data.get("tracking_numbers", [])) > 1 and validated_data.get("address") is None): raise serializers.ValidationError( "address must be specified for multi-shipments pickup", code="required") return validated_data
def dimensions_required_together(value): any_dimension_specified = any( value.get(dim) is not None for dim in DIMENSIONS) has_any_dimension_undefined = any( value.get(dim) is None for dim in DIMENSIONS) if any_dimension_specified and has_any_dimension_undefined: raise serializers.ValidationError( "When one dimension is specified, all must be specified with a dimension_unit" )
def pickup_exists(value): validation = { key: models.Pickup.objects.filter(tracking_number=key).exists() for key in value } if not all(validation.values()): invalids = [key for key, val in validation.items() if val is False] raise serializers.ValidationError( f"Shipment with the tracking numbers: {invalids} not found", code="invalid")
def shipment_exists(value): validation = { key: models.Shipment.objects.filter(tracking_number=key) for key in value } if not all(val.exists() for val in validation.values()): invalids = [ key for key, val in validation.items() if val.exists() is False ] raise serializers.ValidationError( f"Shipment with the tracking numbers: {invalids} not found", code="invalid") if any(val.first().pickup_shipments.exists() for val in validation.values()): scheduled = [ key for key, val in validation.items() if val.first().pickup_shipments.exists() is True ] raise serializers.ValidationError( f"The following shipments {scheduled} are already scheduled pickups", code="invalid", )
def address_exists(value): if value is str and not models.Address.objects.filter(pk=value).exists(): raise serializers.ValidationError( f"Address with id {value} not found: {value}", code="invalid")
def valid_time_format(value): try: datetime.strptime(value, "%H:%M") except Exception: raise serializers.ValidationError("The time format must match HH:HM")