Files

18 lines
1.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export function normalizeCell(value: string) {
const latin=value.replace(/[۰-۹]/g,c=>String('۰۱۲۳۴۵۶۷۸۹'.indexOf(c))).replace(/[٠-٩]/g,c=>String('٠١٢٣٤٥٦٧٨٩'.indexOf(c))).replace(/[\s()-]/g,'');
if(latin.startsWith('09'))return '+98'+latin.slice(1);
if(latin.startsWith('0098'))return '+'+latin.slice(2);
return latin;
}
export function validateContact(input: Record<string,unknown>) {
const fields=['title','name','email','cellNumber','text'] as const;
const data=Object.fromEntries(fields.map(key=>[key,typeof input[key]==='string'?input[key].trim():''])) as Record<typeof fields[number],string>;
const errors:Record<string,string>={};
for(const key of ['title','name','text'] as const)if(!data[key])errors[key]='تکمیل این بخش ضروری است.';
for(const [key,max] of Object.entries({title:200,name:120,email:254,cellNumber:25,text:5000}))if(data[key as keyof typeof data].length>max)errors[key]='متن واردشده بیش از حد طولانی است.';
if(data.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email))errors.email='ایمیل معتبر وارد کنید.';
data.cellNumber=normalizeCell(data.cellNumber);
if(data.cellNumber&&!/^\+[1-9]\d{7,14}$/.test(data.cellNumber))errors.cellNumber='شماره را با ۰۹ یا کد کشور وارد کنید.';
return {data,errors};
}