Murugan_Temple/utils/commonFunction.utils.jsx
Alaguraj0361 4785c22a25
Some checks failed
Build and Deploy Build Output / build (push) Has been cancelled
first commit
2025-11-07 10:51:36 +05:30

325 lines
12 KiB
JavaScript

import { useState } from "react";
const validatePhoneNumber = (phone) => {
// Regex for exactly 10 digits
const phoneRegex = /^\d{10}$/;
return phoneRegex.test(phone);
};
export const validateForm = (formData, validationRules, setErrMsg) => {
const errors = {};
Object.keys(validationRules).forEach((field) => {
const rules = validationRules[field];
const value = formData[field];
if (
rules.required &&
(!value || (typeof value === "string" && value.trim() === ""))
) {
errors[field] = "Enter This Field";
} else if (rules.email && !validateEmail(value)) {
errors[field] = "Invalid Email";
} else if (rules.custom && !rules.custom(value)) {
errors[field] = rules.customMessage || "Invalid value";
} else if (rules.fileType && value && value instanceof File) {
// Validate file type
if (!rules.fileType.includes(value.type)) {
errors[field] = "Invalid file type";
}
// Validate file size
if (rules.fileSize && value.size > rules.fileSize) {
errors[field] = "File is too large";
}
} else if (rules.phoneNumber && !validatePhoneNumber(value)) {
// Validate phone number
errors[field] = "Invalid phone number. Must be exactly 11 digits.";
}
});
setErrMsg(errors);
return Object.keys(errors).length === 0; // Return true if no errors
};
const validateEmail = (email) => {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
};
export const FormField = ({
label,
type,
name,
value,
onChange,
error,
options,
className,
onSubmit,
accept,
placeholder,
required,
checked,
ref,
style,
disabled,
}) => {
const [showPassword, setShowPassword] = useState(false);
const handleTogglePasswordVisibility = () => {
setShowPassword(!showPassword);
};
return (
<>
<div className="relative mb-20">
{label && (
<label style={{ paddingRight: "20px" }}>
{label} {required && <span style={{ color: "red" }}>*</span>}
</label>
)}
{type === "select" ? (
<select
name={name}
onChange={onChange}
value={value}
className={className}
style={style}
>
<option value="" disabled>
Select {placeholder ? placeholder : label}
</option>
{options?.map((option, index) => (
<option key={index} value={option.value}>
{option.label}
</option>
))}
</select>
) : type === "selectbyname" ? (
<select
name={name}
onChange={onChange}
value={value}
className={className}
style={style}
>
<option value="" disabled>
Select {placeholder}
</option>
{options.map((option, index) => (
<option key={index} value={option.label}>
{option.label}
</option>
))}
</select>
) : type === "file" ? (
<input
type="file"
name={name}
ref={ref}
accept={accept}
onChange={onChange}
className={className}
/>
) : type === "password" ? (
<div className="flex items-center" style={{ position: "relative" }}>
<input
type={showPassword ? "text" : "password"}
name={name}
onChange={onChange}
value={value}
className={`${className} flex-grow`}
/>
<button
type="button"
onClick={handleTogglePasswordVisibility}
className="ml-2"
style={{ position: "absolute", right: "10px", top: "22%" }}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<i className="fas fa-eye-slash"></i>
) : (
<i className="fas fa-eye"></i>
)}
</button>
</div>
) : type === "email" ? (
<input
type="email"
name={name}
onChange={onChange}
value={value}
className={className}
disabled={disabled}
placeholder={placeholder}
/>
) : type === "text" ? (
<input
type="text"
name={name}
onChange={onChange}
value={value}
className={className}
disabled={disabled}
placeholder={placeholder}
/>
) : type === "textarea" ? (
<textarea
name={name}
placeholder={label || placeholder}
onChange={onChange}
value={value}
className={className}
style={style}
></textarea>
) : type === "date" ? (
<input
type="date"
name={name}
onChange={onChange}
placeholder={placeholder ? placeholder : label}
value={value}
className={className}
style={style}
/>
) : type === "datetime" ? (
<input
type="datetime-local"
name={name}
onChange={onChange}
placeholder={placeholder ? placeholder : label}
value={value}
className={className}
style={style}
/>
) : type === "tel" ? (
<input
type="tel"
name={name}
onChange={onChange}
value={value}
className={className}
pattern="\d{10}"
maxLength="10"
placeholder={placeholder}
disabled={disabled}
/>
) : type === "radio" ? (
<div className="row">
{options?.map((option, index) => (
<div
key={index}
className="form-radio col-4"
style={{ display: "flex", alignItems: "center" }}
>
<label
htmlFor={`${name}-${option.value}`}
style={{ marginRight: "5px", color: "black" }}
>
{option.label}
</label>
<input
style={{ width: "15%" }}
type="radio"
name={name}
value={option.value}
checked={value === option.value}
onChange={onChange}
className={className}
id={`${name}-${option.value}`}
/>
</div>
))}
</div>
) : type === "checkbox" ? (
<input
type="checkbox"
name={name}
onChange={onChange}
checked={checked}
className="form-checkbox"
id={name}
/>
) : (
<input
type={type}
name={name}
onChange={onChange}
value={value}
className={`${className} custom-input`}
placeholder={placeholder}
style={style}
disabled={disabled}
/>
)}
{error && (
<p className="error" style={{ color: "red", paddingTop: "3px", fontSize: "14px" }}>
{error}
</p>
)}
</div>
<div>
{onSubmit && (
<button className="applicants-search-btn" onClick={onSubmit}>
Search
</button>
)}
</div>
</>
);
};
// export const XLFormat = (data) => {
// // Create a new workbook and add a worksheet
// const wb = XLSX.utils.book_new();
// const ws = XLSX.utils.json_to_sheet(data);
// // Add the worksheet to the workbook
// XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
// // Write the workbook and trigger a download
// XLSX.writeFile(wb, "Applicants Data.xlsx");
// };
// export const downloadExcel = (data) => {
// if (!data || typeof data !== 'object') {
// console.error("Invalid data: Data should be an object.");
// return;
// }
// try {
// // Convert the object to an array of objects
// const formattedData = Object.keys(data).map(key => {
// return { [key]: data[key] }; // Convert object to an array of key-value pairs
// });
// // Now we have an array of objects, each object has a key-value pair from the original object
// const ws = XLSX.utils.json_to_sheet(formattedData); // Convert JSON to worksheet
// const wb = XLSX.utils.book_new(); // Create a new workbook
// XLSX.utils.book_append_sheet(wb, ws, 'Events'); // Append worksheet to workbook
// // Create a Blob with the Excel file and trigger download
// XLSX.writeFile(wb, 'event_data.xlsx');
// } catch (error) {
// console.error("Error during Excel download:", error);
// }
// };
// export const useSetState = (initialState) => {
// const [state, setState] = useState(initialState);
// const newSetState = (newState) => {
// setState((prevState) => ({ ...prevState, ...newState }));
// };
// return [state, newSetState];
// };
// export const Dropdown = (arr, label) => {
// const array = arr?.map((item) => ({ value: item?.id, label: item[label] }));
// return array;
// };