fix(profile-issue-88): auto-update country code on country change and disallow hyphens in phone number #94

Merged
amit merged 1 commits from fix/profile-phone-country-code into main 2026-10-30 05:07:29 +00:00
3 changed files with 150 additions and 46 deletions

View File

@ -105,7 +105,7 @@ export const getCountryRuleByDialCode = (dialCode: string): CountryCode => {
label: dialCode,
country: "Other",
currency: "USD",
minLength: 6,
minLength: 7,
maxLength: 15,
placeholder: "Phone number",
}
@ -125,7 +125,7 @@ export const getCountryRuleByName = (countryName: string): CountryCode => {
label: "🇮🇳 +91",
country: countryName,
currency: normalized === "india" ? "INR" : "USD",
minLength: 6,
minLength: 7,
maxLength: 15,
placeholder: "Phone number",
}
@ -140,10 +140,21 @@ export const validatePhoneNumber = (
if (!val || !val.trim()) return null;
const trimmed = val.trim();
// Explicitly disallow alphabetic characters
if (/[a-zA-Z]/.test(trimmed)) {
return "Phone number cannot contain alphabetic characters.";
}
// Strictly disallow hyphens, dashes, and invalid characters
if (/[\-()_]/.test(trimmed)) {
return "Phone number cannot contain hyphens or special symbols.";
}
// Strictly enforce numeric digits with optional leading '+' and whitespace
if (!/^\+?[\d\s]+$/.test(trimmed)) {
return "Please enter a valid phone number containing only numeric digits.";
}
const allDigits = trimmed.replace(/\D/g, "");
if (allDigits.length === 0) {
return "Please enter a valid phone number with numeric digits.";
@ -160,26 +171,87 @@ export const validatePhoneNumber = (
}
if (rule && rule.country !== "Other") {
const dialDigits = rule.code.replace(/\D/g, "");
let localDigits = allDigits;
// If formatted with country code (e.g. +919876543210 or 919876543210 where total length > rule.maxLength), strip country prefix
if (
(trimmed.startsWith("+") || allDigits.length > rule.maxLength) &&
allDigits.startsWith(dialDigits) &&
allDigits.length === dialDigits.length + rule.minLength
) {
localDigits = allDigits.slice(dialDigits.length);
}
if (rule.minLength === rule.maxLength) {
if (allDigits.length !== rule.minLength) {
if (localDigits.length !== rule.minLength) {
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
}
} else {
if (allDigits.length < rule.minLength) {
if (localDigits.length < rule.minLength) {
return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
}
if (allDigits.length > rule.maxLength) {
if (localDigits.length > rule.maxLength) {
return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
}
}
return null;
}
if (allDigits.length < 6) {
return "Phone number must contain at least 6 digits.";
// General fallback ITU E.164
if (allDigits.length < 7) {
return "Phone number must contain at least 7 digits.";
}
if (allDigits.length > 15) {
return "Phone number cannot exceed 15 digits.";
}
return null;
};
export const isValidPhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): boolean => {
return validatePhoneNumber(val, dialCode, country) === null;
};
/**
* Updates the dial code prefix of an existing phone number when country changes.
* Automatically clamps remaining digits to the new country's maxLength.
*/
export const updatePhoneDialCode = (
currentPhone: string,
oldCountry: string,
newCountry: string
): string => {
const trimmed = currentPhone.trim();
if (!trimmed) return "";
const oldRule = getCountryRuleByName(oldCountry);
const newRule = getCountryRuleByName(newCountry);
// Extract national digits without any dial code
let nationalDigits = "";
if (trimmed.startsWith("+")) {
const matched = [...COUNTRY_CODES]
.sort((a, b) => b.code.length - a.code.length)
.find((c) => trimmed.startsWith(c.code));
if (matched) {
nationalDigits = trimmed.slice(matched.code.length).replace(/\D/g, "");
} else {
nationalDigits = trimmed.replace(/^\+/, "").replace(/\D/g, "");
}
} else {
const oldDialDigits = oldRule.code.replace(/\D/g, "");
const rawDigits = trimmed.replace(/\D/g, "");
if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) {
nationalDigits = rawDigits.slice(oldDialDigits.length);
} else {
nationalDigits = rawDigits;
}
}
const bounded = nationalDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
};

View File

@ -19,6 +19,11 @@ import DropdownField from "@/components/forms/DropdownField";
import FieldLabel from "@/components/forms/FieldLabel";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import { Colors } from "@/theme";
import {
getCountryRuleByName,
updatePhoneDialCode,
validatePhoneNumber,
} from "@/constants/countries";
interface EditProfileFormProps {
initialName?: string;
@ -48,37 +53,32 @@ const COMMON_COUNTRIES = [
"Spain",
];
export const isValidPhoneNumber = (val?: string): boolean => {
export const isValidPhoneNumber = (val?: string, country?: string): boolean => {
if (!val || !val.trim()) return true;
const trimmed = val.trim();
// Must match valid phone character format (optional '+', digits, spaces, hyphens, parentheses)
const phoneRegex = /^\+?[0-9\s\-()]+$/;
if (!phoneRegex.test(trimmed)) {
return false;
}
const digits = trimmed.replace(/\D/g, "");
// ITU-T E.164 standard: minimum 7 and maximum 15 digits
return digits.length >= 7 && digits.length <= 15;
return validatePhoneNumber(val, undefined, country) === null;
};
const cleanPhoneInput = (text: string): string => {
const cleanPhoneInput = (text: string, maxLength = 16): string => {
const trimmedStart = text.trimStart();
const hasPlus = trimmedStart.startsWith("+");
const rest = hasPlus ? trimmedStart.slice(1) : text;
const filtered = rest.replace(/[^0-9\s\-()]/g, "");
// Disallow all non-digits except a single separating space after country code
// Specifically strip hyphens, dashes, parentheses, underscores, and letters
const noDashes = rest.replace(/[\-()_a-zA-Z]/g, "");
const normalized = noDashes.replace(/\s+/g, " ");
let digitCount = 0;
let bounded = "";
for (const ch of filtered) {
let result = "";
for (const ch of normalized) {
if (/\d/.test(ch)) {
if (digitCount < 15) {
if (digitCount < maxLength) {
digitCount++;
bounded += ch;
result += ch;
}
} else {
bounded += ch;
} else if (ch === " " && digitCount > 0 && !result.includes(" ")) {
result += ch;
}
}
return hasPlus ? `+${bounded}` : bounded;
return hasPlus ? `+${result}` : result;
};
export default function EditProfileForm({
@ -96,6 +96,8 @@ export default function EditProfileForm({
const [phoneError, setPhoneError] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const activeRule = getCountryRuleByName(country);
useEffect(() => {
setFullName(initialName);
}, [initialName]);
@ -119,12 +121,22 @@ export default function EditProfileForm({
const cleaned = cleanPhoneInput(text);
setPhone(cleaned);
if (phoneError) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned)) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned, country)) {
setPhoneError("");
}
}
};
const handleCountrySelect = (newCountry: string) => {
if (newCountry !== country) {
const updatedPhone = updatePhoneDialCode(phone, country, newCountry);
setPhone(updatedPhone);
setCountry(newCountry);
if (phoneError) setPhoneError("");
}
setShowCountryModal(false);
};
const handleSave = () => {
let hasError = false;
setNameError("");
@ -137,14 +149,31 @@ export default function EditProfileForm({
}
const trimmedPhone = phone.trim();
if (trimmedPhone && !isValidPhoneNumber(trimmedPhone)) {
setPhoneError("Phone number must be between 7 and 15 digits");
hasError = true;
if (trimmedPhone) {
const rule = getCountryRuleByName(country);
const err = validatePhoneNumber(trimmedPhone, rule.code, country);
if (err) {
setPhoneError(err);
hasError = true;
}
}
if (hasError) return;
onSave?.(trimmedName, trimmedPhone, country);
// Normalize phone before saving: ensure no spaces or hyphens, formatted as +<dialCode><nationalDigits>
let normalizedPhone = "";
if (trimmedPhone) {
const rule = getCountryRuleByName(country);
const digitsOnly = trimmedPhone.replace(/\D/g, "");
const dialDigits = rule.code.replace(/\D/g, "");
let localDigits = digitsOnly;
if (digitsOnly.startsWith(dialDigits) && digitsOnly.length > dialDigits.length) {
localDigits = digitsOnly.slice(dialDigits.length);
}
normalizedPhone = `${rule.code}${localDigits}`;
}
onSave?.(trimmedName, normalizedPhone, country);
};
return (
@ -181,9 +210,9 @@ export default function EditProfileForm({
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder="e.g. +91 9876543210"
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
keyboardType="phone-pad"
maxLength={16}
maxLength={activeRule.maxLength + activeRule.code.length + 2}
textContentType="telephoneNumber"
autoCapitalize="none"
autoCorrect={false}
@ -191,7 +220,9 @@ export default function EditProfileForm({
/>
{!phoneError && (
<Text style={styles.helperText}>
Enter mobile number with country code for login and notifications.
{activeRule.minLength === activeRule.maxLength
? `${activeRule.country} (${activeRule.code}): Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.country} (${activeRule.code}): ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</Text>
)}
</View>
@ -253,10 +284,7 @@ export default function EditProfileForm({
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => {
setCountry(c);
setShowCountryModal(false);
}}
onPress={() => handleCountrySelect(c)}
>
<Text
style={[

View File

@ -16,10 +16,11 @@ import { router } from "expo-router";
import SettingsHeader from "@/features/settings/components/SettingsHeader";
import { Colors } from "@/theme";
import EditProfileForm, { isValidPhoneNumber } from "@/features/profile/components/EditProfileForm";
import EditProfileForm from "@/features/profile/components/EditProfileForm";
import EditProfileAvatar from "@/features/profile/components/EditProfileAvatar";
import { useAuthStore } from "@/store/auth.store";
import { apiClient } from "@/api";
import { getCountryRuleByName, validatePhoneNumber } from "@/constants/countries";
export default function EditProfileScreen() {
const user = useAuthStore((state) => state.user);
@ -40,14 +41,17 @@ export default function EditProfileScreen() {
const trimmedPhone = updatedPhone.trim();
const trimmedCountry = updatedCountry.trim();
if (trimmedPhone && !isValidPhoneNumber(trimmedPhone)) {
const errMsg = "Phone number must be between 7 and 15 digits";
if (Platform.OS === "web") {
window.alert(errMsg);
} else {
Alert.alert("Validation Error", errMsg);
if (trimmedPhone) {
const rule = getCountryRuleByName(trimmedCountry);
const errMsg = validatePhoneNumber(trimmedPhone, rule.code, trimmedCountry);
if (errMsg) {
if (Platform.OS === "web") {
window.alert(errMsg);
} else {
Alert.alert("Validation Error", errMsg);
}
return;
}
return;
}
setSaving(true);