|
| 1 | +const { formatPhoneNumber } = require('./phoneFormat'); |
1 | 2 | const { |
2 | 3 | STANDARD_FORM_FIELD_NAMES, |
3 | 4 | } = require('../../../../@apostrophecms/shared-constants/ui/src/index'); |
@@ -33,38 +34,29 @@ const fieldSpecificSchemas = { |
33 | 34 |
|
34 | 35 | [STANDARD_FORM_FIELD_NAMES.PHONE_NUMBER]: yup |
35 | 36 | .string() |
| 37 | + .trim() |
36 | 38 | .required('Phone number is required') |
37 | | - .max(20, 'Phone number is too long') |
38 | | - .test( |
39 | | - 'phone-format', |
40 | | - 'Enter a valid phone number (e.g., +1 (234) 567-8900)', |
41 | | - (value) => { |
42 | | - if (!value) return false; |
43 | | - |
44 | | - // First check for letters - reject immediately if found |
45 | | - if (/[A-Za-z]/u.test(value)) return false; |
46 | | - |
47 | | - // Remove all non-digit characters except leading + |
48 | | - const digits = value.replace(/\D/gu, ''); |
| 39 | + .test('phone-format', 'Enter a valid phone number', (value, context) => { |
| 40 | + if (/[A-Za-z]/u.test(value)) return false; |
49 | 41 |
|
50 | | - // Check for minimum length (10 digits typical for phone numbers) |
51 | | - if (digits.length < 10) return false; |
52 | | - |
53 | | - // International format: +1 (234) 567-8900 or +1 234 567 8900 or +1.234.567.8900 |
54 | | - const internationalPattern = |
55 | | - /^\+?\d{1,3}[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/u; |
56 | | - // Local format: (234) 567-8900 or 234 567 8900 |
57 | | - const localPattern = /^\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/u; |
58 | | - |
59 | | - // If it starts with +, it must match international pattern |
60 | | - if (value.startsWith('+')) { |
61 | | - return internationalPattern.test(value); |
62 | | - } |
| 42 | + // Check digit length after removing non-digit characters |
| 43 | + const digits = value.replace(/\D/gu, ''); |
| 44 | + if (digits.length < 10) { |
| 45 | + return context.createError({ |
| 46 | + path: context.path, |
| 47 | + message: 'Phone number is too short', |
| 48 | + }); |
| 49 | + } |
| 50 | + if (digits.length > 15) { |
| 51 | + return context.createError({ |
| 52 | + path: context.path, |
| 53 | + message: 'Phone number is too long', |
| 54 | + }); |
| 55 | + } |
63 | 56 |
|
64 | | - // Otherwise check both patterns |
65 | | - return internationalPattern.test(value) || localPattern.test(value); |
66 | | - }, |
67 | | - ), |
| 57 | + const formatted = formatPhoneNumber(value); |
| 58 | + return Boolean(formatted); |
| 59 | + }), |
68 | 60 |
|
69 | 61 | 'g-recaptcha-response': yup |
70 | 62 | .string() |
|
0 commit comments