Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix phone validation for local numbers

Patryk Zawadzki5d06fd2584f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 134ed54d78..97afadeade 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Copy addresses in checkoutCreate and draftOrderCreate mutations - #3866 by @pawelzar
- Fix default product tax rate in Dashboard 1.0 - #3880 by @pawelzar
- Introduce avatars for staff accounts - #3878 by @pawelzar
+- Fix phone number validation in GraphQL when country prefix not given - #3905 by @patrys
## 2.4.0
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index 20b9d7fcf8..7f439f7e02 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -3,12 +3,13 @@ from collections import defaultdict
import i18naddress
from django import forms
from django.forms.forms import BoundField
-from django.utils.translation import pgettext_lazy
+from django.utils.translation import pgettext_lazy, ugettext_lazy as _
from django_countries import countries
-from phonenumber_field.formfields import PhoneNumberField
+from phonenumber_field.phonenumber import PhoneNumber
+from phonenumbers import NumberParseException
+from phonenumbers.phonenumberutil import is_possible_number
from .models import Address
-from .validators import validate_possible_number
from .widgets import DatalistTextWidget, PhonePrefixWidget
COUNTRY_FORMS = {}
@@ -37,13 +38,12 @@ AREA_TYPE_TRANSLATIONS = {
'zip': pgettext_lazy('Address field', 'ZIP code')}
-class PossiblePhoneNumberFormField(PhoneNumberField):
- """A PhoneNumberField that allows phone numbers from other countries."""
+class PossiblePhoneNumberFormField(forms.CharField):
+ """A phone input field."""
- default_validators = [validate_possible_number]
-
- def to_python(self, value):
- return value
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.widget.input_type = 'tel'
class CountryAreaChoiceField(forms.ChoiceField):
@@ -139,6 +139,31 @@ class AddressForm(forms.ModelForm):
field.widget.attrs['placeholder'] = field.label if not hasattr(
field, 'placeholder') else field.placeholder
+ def clean(self):
+ data = super().clean()
+ phone = data.get('phone')
+ country = data.get('country')
+ if phone:
+ try:
+ data['phone'] = clean_phone_for_country(phone, country)
+ except forms.ValidationError as error:
+ self.add_error('phone', error)
+ return data
+
+
+def clean_phone_for_country(phone, country):
+ error = _('The phone number entered is not valid.')
+ error_code = 'invalid_phone_number'
+ if phone:
+ try:
+ phone = PhoneNumber.from_string(phone, country)
+ except NumberParseException:
+ raise forms.ValidationError(error, code=error_code)
+ else:
+ if not is_possible_number(phone):
+ raise forms.ValidationError(error, code=error_code)
+ return phone
+
class CountryAwareAddressForm(AddressForm):
diff --git a/saleor/account/widgets.py b/saleor/account/widgets.py
index d6857861c7..23214ac27a 100644
--- a/saleor/account/widgets.py
+++ b/saleor/account/widgets.py
@@ -21,6 +21,15 @@ class PhonePrefixWidget(PhoneNumberPrefixWidget):
# pylint: disable=bad-super-call
super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)
+ def value_from_datadict(self, data, files, name):
+ value = super().value_from_datadict(
+ data, files, name)
+ # FIXME: this is a hack, we should not be using a multiwidget
+ # in forms used by the API but here we are
+ if not value and name in data:
+ value = data[name]
+ return value
+
class DatalistTextWidget(Select):
template_name = "account/snippets/datalist.html"
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index f1bd639c1f..e78401ed84 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -5,7 +5,8 @@ from django.urls import reverse, reverse_lazy
from django.utils.translation import npgettext_lazy, pgettext_lazy
from ...account.i18n import (
- AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)
+ AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField,
+ clean_phone_for_country)
from ...account.models import User
from ...checkout.forms import QuantityField
from ...core.exceptions import InsufficientStock
@@ -589,6 +590,17 @@ class AddressForm(StorefrontAddressForm):
'Order form: address subform - phone number input field',
'Phone number'))
+ def clean(self):
+ data = super().clean()
+ phone = data.get('phone')
+ country = data.get('country')
+ if phone:
+ try:
+ data['phone'] = clean_phone_for_country(phone, country)
+ except forms.ValidationError as error:
+ self.add_error('phone', error)
+ return data
+
class FulfillmentForm(forms.ModelForm):
"""Create fulfillment group for a given order."""
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index 8d46ff1922..dbcee47ea8 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -38,6 +38,6 @@ class I18nMixin:
return None, errors
if not instance:
instance = Address()
- cls.construct_instance(instance, address_data)
+ cls.construct_instance(instance, address_form.cleaned_data)
cls.clean_instance(instance, errors)
return instance, errors
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index d056ef31cc..6c3ad0c5b8 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -66,7 +66,7 @@ def test_checkout_create(api_client, variant, graphql_address_data):
assert new_cart.shipping_address.postal_code == shipping_address[
'postalCode']
assert new_cart.shipping_address.country == shipping_address['country']
- assert new_cart.shipping_address.city == shipping_address['city']
+ assert new_cart.shipping_address.city == shipping_address['city'].upper()
def test_checkout_create_reuse_cart(cart, user_api_client, variant):
@@ -669,7 +669,52 @@ def test_checkout_shipping_address_update(
'streetAddress2']
assert cart.shipping_address.postal_code == shipping_address['postalCode']
assert cart.shipping_address.country == shipping_address['country']
- assert cart.shipping_address.city == shipping_address['city']
+ assert cart.shipping_address.city == shipping_address['city'].upper()
+
+
+ 'number', [
+ '+48321321888',
+ '+1 (555) 555-5555',
+ '00 44 (0155 55) 5555'
+ ]
+)
+def test_checkout_shipping_address_update_with_phone_country_prefix(
+ number, user_api_client, cart_with_item, graphql_address_data):
+ cart = cart_with_item
+ assert cart.shipping_address is None
+ checkout_id = graphene.Node.to_global_id('Checkout', cart.pk)
+
+ shipping_address = graphql_address_data
+ shipping_address['phone'] = number
+ variables = {
+ 'checkoutId': checkout_id,
+ 'shippingAddress': shipping_address}
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)
+ content = get_graphql_content(response)
+ data = content['data']['checkoutShippingAddressUpdate']
+ assert not data['errors']
+
+
+def test_checkout_shipping_address_update_without_phone_country_prefix(
+ user_api_client, cart_with_item, graphql_address_data):
+ cart = cart_with_item
+ assert cart.shipping_address is None
+ checkout_id = graphene.Node.to_global_id('Checkout', cart.pk)
+
+ shipping_address = graphql_address_data
+ shipping_address['phone'] = '321321888'
+ variables = {
+ 'checkoutId': checkout_id,
+ 'shippingAddress': shipping_address}
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)
+ content = get_graphql_content(response)
+ data = content['data']['checkoutShippingAddressUpdate']
+ assert not data['errors']
def test_checkout_shipping_address_update_invalid_country_code(
@@ -732,7 +777,7 @@ def test_checkout_billing_address_update(
'streetAddress2']
assert cart.billing_address.postal_code == billing_address['postalCode']
assert cart.billing_address.country == billing_address['country']
- assert cart.billing_address.city == billing_address['city']
+ assert cart.billing_address.city == billing_address['city'].upper()
CHECKOUT_EMAIL_UPDATE_MUTATION = """
diff --git a/tests/conftest.py b/tests/conftest.py
index 07d546df76..e44b8789d4 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -95,7 +95,7 @@ def address(db): # pylint: disable=W0613
first_name='John', last_name='Doe',
company_name='Mirumee Software',
street_address_1='Tęczowa 7',
- city='Wrocław',
+ city='WROCŁAW',
postal_code='53-601',
country='PL',
phone='+48713988102')
@@ -107,7 +107,7 @@ def address_other_country():
first_name='John',
last_name='Doe',
street_address_1='4371 Lucas Knoll Apt. 791',
- city='Bennettmouth',
+ city='BENNETTMOUTH',
postal_code='13377',
country='IS',
phone='')
diff --git a/tests/test_account.py b/tests/test_account.py
index b7ff2abdea..08fd6ff69d 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -174,7 +174,7 @@ def test_address_as_data(address):
'company_name': 'Mirumee Software',
'street_address_1': 'Tęczowa 7',
'street_address_2': '',
- 'city': 'Wrocław',
+ 'city': 'WROCŁAW',
'city_area': '',
'postal_code': '53-601',
'country': 'PL',