From dbc0c6070235581d197d5b854bae76b68d4b2ed5 Mon Sep 17 00:00:00 2001
From: Andrew4Coding <andrewdevitoaryo@gmail.com>
Date: Tue, 18 Mar 2025 20:11:58 +0700
Subject: [PATCH] feat: add phone number sanitize and input validation

---
 user/models.py | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/user/models.py b/user/models.py
index b0cbf0d..f28354e 100644
--- a/user/models.py
+++ b/user/models.py
@@ -14,6 +14,17 @@ class ExtendedUser(AbstractUser):
             raise ValidationError('Usia pengguna minimal 12 tahun.')
             
 
+    def validate_and_sanitize_phone(value):
+        phone_regex = RegexValidator(
+            regex=r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$',
+            message='Nomor telepon tidak valid.'
+        )
+        phone_regex(value)
+        
+        # If Success, sanitize input by removing unnecessary characters (+ and -)
+        value = value.replace('(', '').replace(')', '').replace('-', '').replace(' ', '')
+        
+        return value
     
     enum_kategori = {
         'Elektronik': 'Elektronik',
@@ -54,10 +65,7 @@ class ExtendedUser(AbstractUser):
     nomor_hp = models.CharField(
         max_length=15,
         validators=[
-            RegexValidator(
-                regex=r'^62\d{6,13}$',
-                message='Nomor HP harus dalam format (kode negara - nomor telepon) dengan panjang minimal 8 dan maksimal 15. Contoh: 62123456, bukan +62123456 dan 62-12345.'
-            ),
+            validate_and_sanitize_phone
         ]
     )
     email = models.CharField(
-- 
GitLab