UNPKG

emd-utils

Version:
79 lines (71 loc) 2.23 kB
import { constants } from "./constants"; const checks = { isEmpty: (inputValue) => { if (inputValue.length === 0) { return "Input cannot be empty."; } }, isTooShort: (inputValue, length) => { if (inputValue.length < length) { return `Input must be at least ${length} characters long.`; } }, isTooLong: (inputValue, length) => { if (inputValue.length > length) { return `Input cannot be longer than ${length} characters.`; } }, isValidByRegex: (inputValue, regExp, errorMsg) => { if (!regExp.test(inputValue)) { return errorMsg; } }, isNumber: (inputValue) => { if (isNaN(inputValue)) { return "Input must be a number."; } } }; export const validateInput = (fieldType, inputValue) => { const regexList = { [constants.name]: /^[a-zA-Z0-9]*$/, [constants.freeText]: /^[a-zA-Z0-9 ]*$/, }; const fieldRules = { [constants.name]: [ [checks.isEmpty, inputValue], [checks.isTooShort, inputValue, 3], [checks.isTooLong, inputValue, 35], [checks.isValidByRegex, inputValue, regexList[fieldType], "cannot contain special characters or spaces"] ], [constants.freeText]: [ [checks.isEmpty, inputValue], [checks.isTooShort, inputValue, 10], [checks.isTooLong, inputValue, 150], [checks.isValidByRegex, inputValue, regexList[fieldType], "cannot contain special characters"] ], [constants.number]: [ [checks.isEmpty, inputValue], [checks.isNumber, inputValue], [checks.isTooShort, inputValue, 1], [checks.isTooLong, inputValue, 3], ], [constants.code]: [ [checks.isEmpty, inputValue], [checks.isTooShort, inputValue, 1], [checks.isTooLong, inputValue, 5000], ], }; if (!fieldRules[fieldType]) { return { isError: false, errorMessage: "" }; } for (let rule of fieldRules[fieldType]) { const [check, ...params] = rule; const errorMessage = check(...params); if (errorMessage) { return { isError: true, errorMessage }; } } return { isError: false, errorMessage: "" }; }; export default validateInput;