UNPKG

@kubit-ui-web/react-components

Version:

Kubit React Components is a customizable, accessible library of React web components, designed to enhance your application's user experience

42 lines 1.83 kB
import { useState } from 'react'; import { InputTypeType } from '../types/inputType'; import { InternalErrorType } from '../types/internalErrors'; const EMAIL_REGEXP = /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/; // WARNING!!: Use this hook with caution, in general, validations shouldn't be handle internally export const useInternalValidations = (type, minLength, onInternalErrors) => { const [internalErrors, setInternalErrors] = useState([]); const checkInternalValidations = (value) => { const errors = []; // Email validation if (value && type === InputTypeType.EMAIL && !EMAIL_REGEXP.test(value)) { errors.push(InternalErrorType.INVALID_EMAIL); } // Min length validation const minLengthValidation = () => { if (type === InputTypeType.TEXT && minLength && value.length < minLength) { errors.push(InternalErrorType.INVALID_MIN_LENGTH); } }; minLengthValidation(); setInternalErrors(errors); onInternalErrors?.(errors); }; const addInternalError = (internalErrorType) => { const errors = new Set(internalErrors); errors.add(internalErrorType); setInternalErrors(Array.from(errors)); onInternalErrors?.(Array.from(errors)); }; const removeInternalError = (internalErrorType) => { const errors = new Set(internalErrors); errors.forEach(error => { if (error === internalErrorType) { errors.delete(error); } }); setInternalErrors(Array.from(errors)); onInternalErrors?.(Array.from(errors)); }; return { internalErrors, checkInternalValidations, addInternalError, removeInternalError }; }; //# sourceMappingURL=useInternalValidations.js.map