Compare commits

...

1 Commits

Author SHA1 Message Date
ShivaniKhaire 5b5bee72e1 issue 44: dynamic country and phone code selection 2026-10-15 16:43:17 +05:30
5 changed files with 344 additions and 20 deletions

7
package-lock.json generated
View File

@ -32,6 +32,7 @@
"expo-symbols": "~1.0.7", "expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.9", "expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.11", "expo-web-browser": "~15.0.11",
"libphonenumber-js": "^1.13.15",
"react": "19.1.0", "react": "19.1.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-native": "0.81.5", "react-native": "0.81.5",
@ -6185,6 +6186,12 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/libphonenumber-js": {
"version": "1.13.15",
"resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.15.tgz",
"integrity": "sha512-AHdhEQeDFEJ4GKDAQ9AwxChy+v2kUILUB3TGQRpkXMkWePjXTU/WQEzWVQoIx/Gz8fE73Wr5SEuZCy2vk8jrMQ==",
"license": "MIT"
},
"node_modules/lighthouse-logger": { "node_modules/lighthouse-logger": {
"version": "1.4.2", "version": "1.4.2",
"resolved": "https://registry.npmjs.org/lighthouse-logger/-/lighthouse-logger-1.4.2.tgz", "resolved": "https://registry.npmjs.org/lighthouse-logger/-/lighthouse-logger-1.4.2.tgz",

View File

@ -27,6 +27,7 @@
"expo-symbols": "~1.0.7", "expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.9", "expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.11", "expo-web-browser": "~15.0.11",
"libphonenumber-js": "^1.13.15",
"react": "19.1.0", "react": "19.1.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-native": "0.81.5", "react-native": "0.81.5",

View File

@ -19,6 +19,7 @@ interface BaseTextInputProps extends TextInputProps {
label?: string; label?: string;
error?: string; error?: string;
leftIcon?: keyof typeof Ionicons.glyphMap; leftIcon?: keyof typeof Ionicons.glyphMap;
leftElement?: React.ReactNode;
rightElement?: React.ReactNode; rightElement?: React.ReactNode;
} }
@ -28,6 +29,7 @@ const BaseTextInput = forwardRef<TextInput, BaseTextInputProps>(
label, label,
error, error,
leftIcon, leftIcon,
leftElement,
rightElement, rightElement,
style, style,
...props ...props
@ -48,14 +50,16 @@ const BaseTextInput = forwardRef<TextInput, BaseTextInputProps>(
error && styles.errorBorder, error && styles.errorBorder,
]} ]}
> >
{leftIcon && ( {leftElement ? (
leftElement
) : leftIcon ? (
<Ionicons <Ionicons
name={leftIcon} name={leftIcon}
size={moderateScale(20)} size={moderateScale(20)}
color={AuthColors.textSecondary} color={AuthColors.textSecondary}
style={styles.leftIcon} style={styles.leftIcon}
/> />
)} ) : null}
<TextInput <TextInput
ref={ref} ref={ref}

View File

@ -1,36 +1,78 @@
import React, { useState } from "react"; import React, { useMemo, useState } from "react";
import { Alert, StyleSheet, View } from "react-native"; import {
Modal,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { verticalScale } from "react-native-size-matters"; import { Ionicons } from "@expo/vector-icons";
import {
moderateScale,
scale,
verticalScale,
} from "react-native-size-matters";
import BaseTextInput from "@/components/forms/BaseTextInput"; import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput"; import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton"; import PrimaryButton from "@/components/buttons/PrimaryButton";
import { AuthColors } from "@/features/auth/constants/colors";
import { Colors } from "@/theme";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import { register } from "@/features/auth/api/auth.api"; import { register } from "@/features/auth/api/auth.api";
import {
CountryInfo,
getAllCountries,
getDefaultCountry,
validatePhoneByCountry,
} from "@/utils/phone";
export default function SignUpForm() { export default function SignUpForm() {
const router = useRouter(); const router = useRouter();
const setRegisteredUser = useAuthStore((state) => state.setRegisteredUser); const setRegisteredUser = useAuthStore((state) => state.setRegisteredUser);
// ITU डेटाबेसमधून सर्व देश (Zero Hardcoding)
const countries = useMemo(() => getAllCountries(), []);
const [fullName, setFullName] = useState(""); const [fullName, setFullName] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [selectedCountry, setSelectedCountry] = useState<CountryInfo>(getDefaultCountry);
const [phone, setPhone] = useState(""); const [phone, setPhone] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [fullNameError, setFullNameError] = useState(""); const [fullNameError, setFullNameError] = useState("");
const [emailError, setEmailError] = useState(""); const [emailError, setEmailError] = useState("");
const [phoneError, setPhoneError] = useState(""); const [phoneError, setPhoneError] = useState("");
const [passwordError, setPasswordError] = useState(""); const [passwordError, setPasswordError] = useState("");
const [confirmPasswordError, setConfirmPasswordError] = useState(""); const [confirmPasswordError, setConfirmPasswordError] = useState("");
// युझर फक्त आकडे टाईप करेल (+91 नाही)
const handlePhoneChange = (text: string) => { const handlePhoneChange = (text: string) => {
const digits = text.replace(/\D/g, ""); const digits = text.replace(/\D/g, "");
setPhone(digits.slice(0, 10)); setPhone(digits.slice(0, 15));
if (phoneError) setPhoneError("");
}; };
// सर्च बार फिल्टर
const filteredCountries = useMemo(() => {
if (!searchQuery.trim()) return countries;
const query = searchQuery.toLowerCase().trim();
return countries.filter(
(c) =>
c.name.toLowerCase().includes(query) ||
c.dialCode.includes(query) ||
c.iso.toLowerCase().includes(query)
);
}, [countries, searchQuery]);
const handleSignUp = async () => { const handleSignUp = async () => {
let hasError = false; let hasError = false;
setFullNameError(""); setFullNameError("");
@ -52,9 +94,13 @@ export default function SignUpForm() {
hasError = true; hasError = true;
} }
if (phone.trim() && phone.length < 10) { // ITU लायब्ररीद्वारे डायनॅमिक फोन व्हॅलिडेशन
setPhoneError("Phone number must be 10 digits"); if (phone.trim()) {
hasError = true; const isValid = validatePhoneByCountry(phone.trim(), selectedCountry.iso);
if (!isValid) {
setPhoneError(`Please enter a valid ${selectedCountry.name} phone number`);
hasError = true;
}
} }
if (!password) { if (!password) {
@ -87,23 +133,29 @@ export default function SignUpForm() {
if (hasError) return; if (hasError) return;
// पूर्ण आंतरराष्ट्रीय नंबर तयार करणे
const fullPhoneNumber = phone.trim()
? `${selectedCountry.dialCode} ${phone.trim()}`
: undefined;
try { try {
const response = await register({ const response = await register({
email: email.trim().toLowerCase(), email: email.trim().toLowerCase(),
password, password,
full_name: fullName.trim(), full_name: fullName.trim(),
phone_number: phone.trim() ? phone.trim() : undefined, phone_number: fullPhoneNumber,
country: selectedCountry.name, // DB मध्ये सेव्ह होणारा देश
}); });
const { user } = response; const { user } = response;
setRegisteredUser({ setRegisteredUser({
id: user.id, id: user.id,
name: user.display_name, name: user.display_name || fullName.trim(),
email: user.email, email: user.email,
phone_number: user.phone_number || undefined,
country: user.country || selectedCountry.name,
}); });
// Redirect directly to login screen without alert block
router.replace("/login"); router.replace("/login");
} catch (err: any) { } catch (err: any) {
let errMsg = "Something went wrong. Please try again."; let errMsg = "Something went wrong. Please try again.";
@ -141,17 +193,35 @@ export default function SignUpForm() {
error={emailError} error={emailError}
/> />
{/* Direct Phone Number Input with In-Line Country Prefix Badge */}
<BaseTextInput <BaseTextInput
value={phone} value={phone}
onChangeText={handlePhoneChange} onChangeText={handlePhoneChange}
placeholder="Phone Number (Optional)" placeholder="Mobile Number (Optional)"
keyboardType="number-pad" keyboardType="number-pad"
autoCapitalize="none" autoCapitalize="none"
autoCorrect={false} autoCorrect={false}
textContentType="telephoneNumber" textContentType="telephoneNumber"
maxLength={10} maxLength={15}
leftIcon="call-outline"
error={phoneError} error={phoneError}
leftElement={
<Pressable
style={styles.countryBadge}
onPress={() => setShowCountryModal(true)}
accessibilityRole="button"
accessibilityLabel="Select country code"
>
<Text style={styles.countryBadgeFlag}>{selectedCountry.flag}</Text>
<Text style={styles.countryBadgeCode}>{selectedCountry.dialCode}</Text>
<Ionicons
name="chevron-down"
size={moderateScale(12)}
color={AuthColors.textSecondary}
style={styles.countryBadgeArrow}
/>
<View style={styles.divider} />
</Pressable>
}
/> />
<PasswordInput <PasswordInput
@ -169,11 +239,79 @@ export default function SignUpForm() {
/> />
<View style={styles.buttonSpacing}> <View style={styles.buttonSpacing}>
<PrimaryButton <PrimaryButton title="Sign Up" onPress={handleSignUp} />
title="Sign Up"
onPress={handleSignUp}
/>
</View> </View>
{/* Searchable Country Picker Modal */}
<Modal
visible={showCountryModal}
transparent
animationType="slide"
onRequestClose={() => setShowCountryModal(false)}
>
<Pressable
style={styles.modalOverlay}
onPress={() => setShowCountryModal(false)}
>
<View style={styles.modalSheet} onStartShouldSetResponder={() => true}>
<View style={styles.modalHeader}>
<Text style={styles.modalTitle}>Select Country</Text>
<Pressable hitSlop={8} onPress={() => setShowCountryModal(false)}>
<Ionicons name="close" size={moderateScale(22)} color={Colors.textSecondary} />
</Pressable>
</View>
{/* २४०+ देशांमधून शोधण्यासाठी Search Box */}
<View style={styles.searchBox}>
<Ionicons name="search" size={moderateScale(18)} color={AuthColors.textSecondary} />
<TextInput
value={searchQuery}
onChangeText={setSearchQuery}
placeholder="Search country or code..."
placeholderTextColor={AuthColors.textSecondary}
style={styles.searchInput}
autoCorrect={false}
/>
{searchQuery ? (
<Pressable onPress={() => setSearchQuery("")}>
<Ionicons name="close-circle" size={moderateScale(16)} color={AuthColors.textSecondary} />
</Pressable>
) : null}
</View>
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.countryList}>
{filteredCountries.map((item) => {
const isSelected = selectedCountry.iso === item.iso;
return (
<Pressable
key={item.iso}
style={({ pressed }) => [
styles.countryItem,
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => {
setSelectedCountry(item);
setShowCountryModal(false);
setSearchQuery("");
}}
>
<Text style={[styles.countryName, isSelected && styles.countryNameSelected]}>
{item.flag} {item.name}
</Text>
<View style={styles.codeRow}>
<Text style={styles.countryCodeText}>{item.dialCode}</Text>
{isSelected && (
<Ionicons name="checkmark" size={moderateScale(18)} color={Colors.primary} />
)}
</View>
</Pressable>
);
})}
</ScrollView>
</View>
</Pressable>
</Modal>
</View> </View>
); );
} }
@ -185,4 +323,113 @@ const styles = StyleSheet.create({
buttonSpacing: { buttonSpacing: {
marginTop: verticalScale(10), marginTop: verticalScale(10),
}, },
// Country Prefix Badge
countryBadge: {
flexDirection: "row",
alignItems: "center",
paddingRight: scale(8),
},
countryBadgeFlag: {
fontSize: moderateScale(16),
marginRight: scale(4),
},
countryBadgeCode: {
fontSize: moderateScale(14),
fontWeight: "600",
color: AuthColors.textPrimary,
},
countryBadgeArrow: {
marginLeft: scale(3),
},
divider: {
width: 1,
height: verticalScale(20),
backgroundColor: AuthColors.border,
marginLeft: scale(8),
},
// Modal Styles
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.4)",
justifyContent: "flex-end",
},
modalSheet: {
backgroundColor: "#FFFFFF",
borderTopLeftRadius: moderateScale(20),
borderTopRightRadius: moderateScale(20),
maxHeight: "75%",
paddingTop: verticalScale(16),
paddingBottom: verticalScale(32),
},
modalHeader: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: scale(20),
paddingBottom: verticalScale(12),
borderBottomWidth: 1,
borderBottomColor: "#F1F5F9",
},
modalTitle: {
fontSize: moderateScale(17),
fontWeight: "700",
color: Colors.textPrimary,
},
searchBox: {
flexDirection: "row",
alignItems: "center",
backgroundColor: AuthColors.inputBackground,
marginHorizontal: scale(16),
marginVertical: verticalScale(10),
paddingHorizontal: scale(12),
borderRadius: moderateScale(12),
height: verticalScale(42),
borderWidth: 1,
borderColor: AuthColors.border,
},
searchInput: {
flex: 1,
marginLeft: scale(8),
fontSize: moderateScale(14),
color: AuthColors.textPrimary,
},
countryList: {
paddingHorizontal: scale(16),
paddingTop: verticalScale(4),
},
countryItem: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingVertical: verticalScale(12),
paddingHorizontal: scale(12),
borderRadius: moderateScale(10),
},
countryItemSelected: {
backgroundColor: "#DCFCE7",
},
countryItemPressed: {
backgroundColor: "#F1F5F9",
},
countryName: {
fontSize: moderateScale(14),
color: Colors.textPrimary,
fontWeight: "500",
},
countryNameSelected: {
fontWeight: "700",
color: Colors.primaryDark,
},
codeRow: {
flexDirection: "row",
alignItems: "center",
gap: scale(8),
},
countryCodeText: {
fontSize: moderateScale(13),
color: Colors.textSecondary,
fontWeight: "600",
},
}); });

65
src/utils/phone.ts Normal file
View File

@ -0,0 +1,65 @@
import {
CountryCode,
getCountries,
getCountryCallingCode,
isValidPhoneNumber as checkValidPhone,
} from "libphonenumber-js";
export interface CountryInfo {
iso: CountryCode;
name: string;
dialCode: string;
flag: string;
}
const displayNames = new Intl.DisplayNames(["en"], { type: "region" });
export const getFlagEmoji = (iso: string): string => {
const upper = iso.toUpperCase();
if (upper.length !== 2) return "🌐";
return String.fromCodePoint(
127397 + upper.charCodeAt(0),
127397 + upper.charCodeAt(1)
);
};
export const getAllCountries = (): CountryInfo[] => {
return getCountries()
.map((iso) => {
let dialCode = "";
try {
dialCode = `+${getCountryCallingCode(iso)}`;
} catch {
dialCode = "";
}
return {
iso,
name: displayNames.of(iso) || iso,
dialCode,
flag: getFlagEmoji(iso),
};
})
.filter((c) => c.dialCode !== "")
.sort((a, b) => a.name.localeCompare(b.name));
};
export const getDefaultCountry = (): CountryInfo => {
return {
iso: "IN",
name: "India",
dialCode: "+91",
flag: getFlagEmoji("IN"),
};
};
export const validatePhoneByCountry = (
phoneNumber: string,
countryIso: CountryCode
): boolean => {
if (!phoneNumber || !phoneNumber.trim()) return true;
try {
return checkValidPhone(phoneNumber, countryIso);
} catch {
return false;
}
};