MongoEngine / mongoengine

A Python Object-Document-Mapper for working with MongoDB
http://mongoengine.org
MIT License
4.24k stars 1.23k forks source link

Phone field missing on model #1495

Closed marcoller closed 5 years ago

marcoller commented 7 years ago

Hello,

we've seen that a phone field does not exist on the mongoengine models. We have added it and that is the code resulting from the git diff on the fields.py file:

diff --git a/mongoengine/fields.py b/mongoengine/fields.py
index 1142509..c6f539d 100644
--- a/mongoengine/fields.py
+++ b/mongoengine/fields.py
@@ -39,7 +39,7 @@ except ImportError:
     ImageOps = None

 __all__ = (
-    'StringField', 'URLField', 'EmailField', 'IntField', 'LongField',
+    'StringField', 'URLField', 'EmailField', 'PhoneField', 'IntField', 'LongField',
     'FloatField', 'DecimalField', 'BooleanField', 'DateTimeField',
     'ComplexDateTimeField', 'EmbeddedDocumentField', 'ObjectIdField',
     'GenericEmbeddedDocumentField', 'DynamicField', 'ListField',
@@ -169,6 +169,18 @@ class EmailField(StringField):
         super(EmailField, self).validate(value)

+class PhoneField(StringField):
+    """
+    A field that validates input as phone.
+    """
+    PHONE_REGEX = re.compile("^\+[1-9]{1}[0-9]{3,14}$")
+
+    def validate(self, value):
+        if not PhoneField.PHONE_REGEX.match(value):
+            self.error('Invalid phone number: %s' % value)
+        super(PhoneField, self).validate(value)
+
+
 class IntField(BaseField):
     """32-bit integer field."""
wojcikstefan commented 7 years ago

Hi @marcoller I think this might be an overly simplistic approach to validating phone numbers (e.g. right now it would accept number extensions like +16503334444x1234). Phone validation is actually a pretty complex problem that has its own set of libraries, for instance https://github.com/daviddrysdale/python-phonenumbers.

Depending on one's use case it might be fine to choose this simpler approach or it might not. I'm a bit weary to add a PhoneField that might fail to support some valid phone numbers.

bagerard commented 5 years ago

Let's close this issue as it is quite old and didn't get much attention. For future ref, note that django does not have a builtin phone field, there is another package (django-phone-field) that offers support