feat: introduce reusable CustomInput and CustomTextArea components with built-in validation support
This commit is contained in:
@@ -157,6 +157,7 @@ export function FieldDefinitionFormModal({
|
||||
...prev,
|
||||
fieldType: newType,
|
||||
lookupSource: isLookupType ? prev.lookupSource : undefined,
|
||||
validationJson: isLookupType ? undefined : prev.validationJson,
|
||||
}));
|
||||
if (setError && !isLookupType) {
|
||||
setError(null);
|
||||
@@ -235,6 +236,7 @@ export function FieldDefinitionFormModal({
|
||||
/>
|
||||
|
||||
{/* Validation JSON Rules */}
|
||||
{formData.fieldType !== 'dropdown' && formData.fieldType !== 'multi_select' && (
|
||||
<div className="p-4 bg-slate-50 border border-slate-200 rounded-[14px] space-y-3">
|
||||
<h5 className="text-[13px] font-bold text-slate-800">Validation Rules (validation_json)</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
@@ -286,6 +288,7 @@ export function FieldDefinitionFormModal({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Conditional Visibility */}
|
||||
<div className="p-4 bg-amber-50/60 border border-amber-200 rounded-[14px] space-y-3">
|
||||
|
||||
@@ -1394,24 +1394,29 @@ export default function AddPolicyEngine() {
|
||||
const fieldVal = action.fieldValues?.[field.fieldCode];
|
||||
const lookupOpts = fieldLookupOptionsMap[field.lookupSource || ''] || [];
|
||||
const helpText = field.helpText || (field as any).help_text;
|
||||
const valRules = field.validationJson || (field as any).validation_json;
|
||||
|
||||
return (
|
||||
<div key={field.id} className={widthClass}>
|
||||
<label className="block text-[13px] font-semibold text-slate-700 mb-1.5">
|
||||
{field.fieldName}
|
||||
{field.isRequired && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
|
||||
{field.fieldType === 'textarea' ? (
|
||||
<CustomTextArea
|
||||
label={field.fieldName}
|
||||
required={field.isRequired}
|
||||
validationJson={valRules}
|
||||
value={fieldVal || ''}
|
||||
onChange={(e) => handleFieldValueChange(rule.id, action.id, field.fieldCode, e.target.value)}
|
||||
placeholder={field.placeholder || 'Enter details...'}
|
||||
/>
|
||||
) : field.fieldType === 'currency' ? (
|
||||
<div>
|
||||
<label className="block text-[13px] font-semibold text-slate-700 mb-1.5">
|
||||
{field.fieldName}
|
||||
{field.isRequired && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="col-span-2">
|
||||
<CustomInput
|
||||
validationJson={valRules}
|
||||
type="number"
|
||||
value={fieldVal?.amount || ''}
|
||||
onChange={(e) =>
|
||||
@@ -1434,8 +1439,11 @@ export default function AddPolicyEngine() {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : field.fieldType === 'dropdown' ? (
|
||||
<CustomDropdown
|
||||
label={field.fieldName}
|
||||
required={field.isRequired}
|
||||
options={lookupOpts}
|
||||
value={fieldVal || ''}
|
||||
onChange={(val) => handleFieldValueChange(rule.id, action.id, field.fieldCode, val)}
|
||||
@@ -1443,6 +1451,8 @@ export default function AddPolicyEngine() {
|
||||
/>
|
||||
) : field.fieldType === 'multi_select' ? (
|
||||
<CustomMultiSelect
|
||||
label={field.fieldName}
|
||||
required={field.isRequired}
|
||||
options={lookupOpts}
|
||||
value={Array.isArray(fieldVal) ? fieldVal : []}
|
||||
onChange={(vals) => handleFieldValueChange(rule.id, action.id, field.fieldCode, vals)}
|
||||
@@ -1455,6 +1465,11 @@ export default function AddPolicyEngine() {
|
||||
label={field.fieldName}
|
||||
/>
|
||||
) : field.fieldType === 'switch' ? (
|
||||
<div>
|
||||
<label className="block text-[13px] font-semibold text-slate-700 mb-1.5">
|
||||
{field.fieldName}
|
||||
{field.isRequired && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<CustomSwitch
|
||||
checked={!!fieldVal}
|
||||
@@ -1464,8 +1479,12 @@ export default function AddPolicyEngine() {
|
||||
{fieldVal ? 'Enabled' : 'Disabled'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<CustomInput
|
||||
label={field.fieldName}
|
||||
required={field.isRequired}
|
||||
validationJson={valRules}
|
||||
type={
|
||||
field.fieldType === 'number' || field.fieldType === 'decimal' || field.fieldType === 'percentage'
|
||||
? 'number'
|
||||
|
||||
@@ -200,7 +200,7 @@ export default function PolicyEngineList() {
|
||||
className: "text-right",
|
||||
accessor: (row) => (
|
||||
<CustomActionMenu>
|
||||
{row.status !== "Active" && (
|
||||
{row.status?.toLowerCase() === "inactive" && (
|
||||
<CustomActionItem
|
||||
icon={<ChecksIcon size={15} />}
|
||||
variant="success"
|
||||
@@ -209,7 +209,7 @@ export default function PolicyEngineList() {
|
||||
Activate
|
||||
</CustomActionItem>
|
||||
)}
|
||||
{row.status === "Active" && (
|
||||
{row.status?.toLowerCase() === "active" && (
|
||||
<CustomActionItem
|
||||
icon={<XIcon size={15} />}
|
||||
onClick={() => setDeactivateTarget(row)}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import React, { useState, forwardRef } from "react";
|
||||
import React, { useState, forwardRef, useEffect } from "react";
|
||||
import { PhoneIcon, EyeIcon, EyeSlashIcon } from "@phosphor-icons/react";
|
||||
|
||||
type InputType = "text" | "password" | "number" | "email" | "tel" | "date" | "month" | "datetime-local" | "time";
|
||||
|
||||
export interface ValidationJsonRule {
|
||||
min?: number;
|
||||
max?: number;
|
||||
regex?: string;
|
||||
}
|
||||
|
||||
interface CustomInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size"> {
|
||||
label?: string;
|
||||
type?: InputType;
|
||||
@@ -13,6 +19,7 @@ interface CustomInputProps extends Omit<React.InputHTMLAttributes<HTMLInputEleme
|
||||
error?: string;
|
||||
containerClassName?: string;
|
||||
size?: "sm" | "md" | "lg";
|
||||
validationJson?: ValidationJsonRule | string;
|
||||
}
|
||||
|
||||
const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
@@ -29,7 +36,9 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
containerClassName = "",
|
||||
error,
|
||||
onInput,
|
||||
onChange,
|
||||
size = "md",
|
||||
validationJson,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
@@ -37,6 +46,7 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
const isPassword = type === "password";
|
||||
const isPhone = phonePrefix !== undefined;
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [validationError, setValidationError] = useState<string>("");
|
||||
|
||||
const inputType = isPassword && showPassword ? "text" : type;
|
||||
|
||||
@@ -46,16 +56,101 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
lg: "py-3 text-base h-[48px]",
|
||||
};
|
||||
|
||||
const parsedValJson: ValidationJsonRule | null = (() => {
|
||||
if (!validationJson) return null;
|
||||
if (typeof validationJson === "string") {
|
||||
try {
|
||||
return JSON.parse(validationJson);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return validationJson;
|
||||
})();
|
||||
|
||||
const effectiveMax = parsedValJson?.max !== undefined ? Number(parsedValJson.max) : maxLength;
|
||||
const effectiveMin = parsedValJson?.min !== undefined ? Number(parsedValJson.min) : undefined;
|
||||
const effectiveRegex = parsedValJson?.regex || undefined;
|
||||
|
||||
const validateInput = (val: string) => {
|
||||
const fieldLabel = label ? `"${label}"` : "This field";
|
||||
|
||||
// 1. Max length / value check
|
||||
if (effectiveMax !== undefined && effectiveMax > 0) {
|
||||
if (type === "number") {
|
||||
if (val !== "" && Number(val) > effectiveMax) {
|
||||
setValidationError(`${fieldLabel} cannot be greater than ${effectiveMax}`);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (val.length >= effectiveMax) {
|
||||
setValidationError(`${fieldLabel} cannot exceed ${effectiveMax} characters`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Min length / value check
|
||||
if (effectiveMin !== undefined && effectiveMin > 0) {
|
||||
if (type === "number") {
|
||||
if (val !== "" && Number(val) < effectiveMin) {
|
||||
setValidationError(`${fieldLabel} must be at least ${effectiveMin}`);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (val.length > 0 && val.length < effectiveMin) {
|
||||
setValidationError(`${fieldLabel} must be at least ${effectiveMin} characters`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Regex check
|
||||
if (effectiveRegex && val.length > 0) {
|
||||
try {
|
||||
const reg = new RegExp(effectiveRegex, "u");
|
||||
if (!reg.test(val)) {
|
||||
setValidationError(`Invalid format for ${fieldLabel}`);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid regex string syntax
|
||||
}
|
||||
}
|
||||
|
||||
setValidationError("");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (props.value !== undefined && props.value !== null) {
|
||||
validateInput(String(props.value));
|
||||
}
|
||||
}, [props.value, effectiveMax, effectiveMin, effectiveRegex, label]);
|
||||
|
||||
const handleInput = (e: React.FormEvent<HTMLInputElement>) => {
|
||||
if (maxLength && (type === "number" || type === "tel")) {
|
||||
const target = e.target as HTMLInputElement;
|
||||
if (target.value.length > maxLength) {
|
||||
target.value = target.value.slice(0, maxLength);
|
||||
if (effectiveMax && (type === "number" || type === "tel")) {
|
||||
if (target.value.length > effectiveMax) {
|
||||
target.value = target.value.slice(0, effectiveMax);
|
||||
}
|
||||
}
|
||||
validateInput(target.value);
|
||||
onInput?.(e as any);
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
if (effectiveMax && (type === "number" || type === "tel")) {
|
||||
if (target.value.length > effectiveMax) {
|
||||
target.value = target.value.slice(0, effectiveMax);
|
||||
}
|
||||
}
|
||||
validateInput(target.value);
|
||||
onChange?.(e);
|
||||
};
|
||||
|
||||
const displayError = error || validationError;
|
||||
|
||||
return (
|
||||
<div className={`w-full flex flex-col gap-1.5 ${containerClassName}`}>
|
||||
{label && (
|
||||
@@ -88,9 +183,10 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
ref={ref}
|
||||
type={inputType}
|
||||
maxLength={
|
||||
type === "number" || type === "tel" ? undefined : maxLength
|
||||
type === "number" || type === "tel" ? undefined : effectiveMax
|
||||
}
|
||||
onInput={handleInput}
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
className={`
|
||||
${isPhone
|
||||
@@ -98,7 +194,7 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
: `
|
||||
w-full rounded-lg
|
||||
bg-white text-gray-900
|
||||
border ${error ? "border-red-500" : "border-gray-300"}
|
||||
border ${displayError ? "border-red-500" : "border-gray-300"}
|
||||
px-3 ${sizeClasses[size]}
|
||||
outline-none
|
||||
transition-all duration-200
|
||||
@@ -131,7 +227,7 @@ const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="text-xs text-red-500 mt-1">{error}</p>}
|
||||
{displayError && <p className="text-xs text-red-500 mt-1">{displayError}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import React, { forwardRef } from "react";
|
||||
import React, { useState, forwardRef, useEffect } from "react";
|
||||
|
||||
export interface ValidationJsonRule {
|
||||
min?: number;
|
||||
max?: number;
|
||||
regex?: string;
|
||||
}
|
||||
|
||||
interface CustomTextAreaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
|
||||
@@ -8,6 +14,7 @@ interface CustomTextAreaProps
|
||||
maxLength?: number;
|
||||
error?: string;
|
||||
size?: "sm" | "md" | "lg";
|
||||
validationJson?: ValidationJsonRule | string;
|
||||
}
|
||||
|
||||
const CustomTextArea = forwardRef<HTMLTextAreaElement, CustomTextAreaProps>(
|
||||
@@ -21,16 +28,90 @@ const CustomTextArea = forwardRef<HTMLTextAreaElement, CustomTextAreaProps>(
|
||||
className = "",
|
||||
rows = 4,
|
||||
size = "md",
|
||||
error,
|
||||
onInput,
|
||||
onChange,
|
||||
validationJson,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [validationError, setValidationError] = useState<string>("");
|
||||
|
||||
const sizeClasses = {
|
||||
sm: "py-2 text-sm",
|
||||
md: "py-2.5 text-sm",
|
||||
lg: "py-3 text-base",
|
||||
};
|
||||
|
||||
const parsedValJson: ValidationJsonRule | null = (() => {
|
||||
if (!validationJson) return null;
|
||||
if (typeof validationJson === "string") {
|
||||
try {
|
||||
return JSON.parse(validationJson);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return validationJson;
|
||||
})();
|
||||
|
||||
const effectiveMax = parsedValJson?.max !== undefined ? Number(parsedValJson.max) : maxLength;
|
||||
const effectiveMin = parsedValJson?.min !== undefined ? Number(parsedValJson.min) : undefined;
|
||||
const effectiveRegex = parsedValJson?.regex || undefined;
|
||||
|
||||
const validateInput = (val: string) => {
|
||||
const fieldLabel = label ? `"${label}"` : "This field";
|
||||
|
||||
if (effectiveMax !== undefined && effectiveMax > 0) {
|
||||
if (val.length >= effectiveMax) {
|
||||
setValidationError(`${fieldLabel} cannot exceed ${effectiveMax} characters`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveMin !== undefined && effectiveMin > 0) {
|
||||
if (val.length > 0 && val.length < effectiveMin) {
|
||||
setValidationError(`${fieldLabel} must be at least ${effectiveMin} characters`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveRegex && val.length > 0) {
|
||||
try {
|
||||
const reg = new RegExp(effectiveRegex, "u");
|
||||
if (!reg.test(val)) {
|
||||
setValidationError(`Invalid format for ${fieldLabel}`);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid regex string syntax
|
||||
}
|
||||
}
|
||||
|
||||
setValidationError("");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (props.value !== undefined && props.value !== null) {
|
||||
validateInput(String(props.value));
|
||||
}
|
||||
}, [props.value, effectiveMax, effectiveMin, effectiveRegex, label]);
|
||||
|
||||
const handleInput = (e: React.FormEvent<HTMLTextAreaElement>) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
validateInput(target.value);
|
||||
onInput?.(e as any);
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
validateInput(target.value);
|
||||
onChange?.(e);
|
||||
};
|
||||
|
||||
const displayError = error || validationError;
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-1.5">
|
||||
{label && (
|
||||
@@ -50,12 +131,14 @@ const CustomTextArea = forwardRef<HTMLTextAreaElement, CustomTextAreaProps>(
|
||||
<textarea
|
||||
ref={ref}
|
||||
rows={rows}
|
||||
maxLength={maxLength}
|
||||
maxLength={effectiveMax}
|
||||
onInput={handleInput}
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
className={`
|
||||
w-full rounded-lg
|
||||
bg-white text-gray-900
|
||||
border ${props.error ? 'border-red-500' : 'border-gray-300'}
|
||||
border ${displayError ? 'border-red-500' : 'border-gray-300'}
|
||||
px-3 ${sizeClasses[size]}
|
||||
outline-none
|
||||
transition-all duration-200
|
||||
@@ -77,7 +160,7 @@ const CustomTextArea = forwardRef<HTMLTextAreaElement, CustomTextAreaProps>(
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{props.error && <p className="text-xs text-red-500 mt-1">{props.error}</p>}
|
||||
{displayError && <p className="text-xs text-red-500 mt-1">{displayError}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user