├── src ├── index.ts ├── vite-env.d.ts ├── testing-env │ ├── main.tsx │ └── App.tsx ├── utils │ ├── useRunAfterUpdate.ts │ ├── useRunAfterUpdate.test.ts │ ├── index.ts │ └── index.test.ts └── hook │ ├── useInputMask.tsx │ └── useInputMask.test.tsx ├── vitest.config.ts ├── SECURITY.MD ├── index.html ├── .eslintrc.cjs ├── vite.dev.config.ts ├── LICENSE ├── vite.config.ts ├── package.json ├── .gitignore ├── CODE_OF_CONDUCT.md ├── README.md └── tsconfig.json /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./hook/useInputMask"; 2 | -------------------------------------------------------------------------------- /src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vitest/config"; 2 | 3 | export default defineConfig({ 4 | test: { 5 | globals: true, 6 | environment: "happy-dom", 7 | }, 8 | }); 9 | -------------------------------------------------------------------------------- /src/testing-env/main.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom/client"; 3 | import { App } from "./App"; 4 | 5 | ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( 6 | 7 | 8 | 9 | ); 10 | -------------------------------------------------------------------------------- /SECURITY.MD: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | 1.0.x | :white_check_mark: | 8 | 9 | ## Reporting a Vulnerability 10 | 11 | In case of a vulnerability please reach out to active maintainers of the project and report it to them. -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Vite + React + TS 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { browser: true, es2020: true }, 3 | extends: [ 4 | "eslint:recommended", 5 | "plugin:@typescript-eslint/recommended", 6 | "plugin:react-hooks/recommended", 7 | ], 8 | parser: "@typescript-eslint/parser", 9 | parserOptions: { ecmaVersion: "latest", sourceType: "module" }, 10 | plugins: ["react-refresh"], 11 | rules: { 12 | "react-refresh/only-export-components": "warn", 13 | "@typescript-eslint/no-non-null-assertion": "off", 14 | "@typescript-eslint/ban-ts-comment": "off", 15 | }, 16 | }; 17 | -------------------------------------------------------------------------------- /vite.dev.config.ts: -------------------------------------------------------------------------------- 1 | // vite.config.js 2 | import { resolve } from "path"; 3 | import { defineConfig } from "vite"; 4 | import react from "@vitejs/plugin-react"; 5 | 6 | export default defineConfig({ 7 | plugins: [react()], 8 | build: { 9 | lib: { 10 | entry: resolve(__dirname, "src/index.ts"), 11 | name: "React input mask", 12 | fileName: "index", 13 | }, 14 | rollupOptions: { 15 | external: ["react", "react-dom"], 16 | output: { 17 | globals: { 18 | react: "React", 19 | }, 20 | }, 21 | }, 22 | }, 23 | }); 24 | -------------------------------------------------------------------------------- /src/testing-env/App.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useInputMask } from "../hook/useInputMask"; 3 | import { useForm } from "react-hook-form"; 4 | 5 | const App = () => { 6 | const { register, watch } = useForm(); 7 | const regArgs = register("test"); 8 | const inputProps = useInputMask({ 9 | mask: "9999 9999 9999 9999", 10 | placeholderChar: "_", 11 | type: "raw", 12 | value: "9999999999999999", 13 | }); 14 | const test = watch("test"); 15 | console.log(test); 16 | return ( 17 |
18 | 19 |
20 | ); 21 | }; 22 | 23 | export { App }; 24 | -------------------------------------------------------------------------------- /src/utils/useRunAfterUpdate.ts: -------------------------------------------------------------------------------- 1 | import { useRef, useEffect, useLayoutEffect } from "react"; 2 | 3 | const canUseDOM = typeof window !== "undefined"; 4 | const useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect; 5 | 6 | export const useRunAfterUpdate = () => { 7 | const afterPaintRef = useRef<() => void | undefined>(); 8 | useIsomorphicLayoutEffect(() => { 9 | if (afterPaintRef.current) { 10 | afterPaintRef.current(); 11 | afterPaintRef.current = undefined; 12 | } 13 | }); 14 | const runAfterUpdate = (fn: () => void) => { 15 | afterPaintRef.current = fn; 16 | }; 17 | 18 | return runAfterUpdate; 19 | }; 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Code Forge 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | // vite.config.js 2 | import { resolve } from "path"; 3 | import { defineConfig } from "vite"; 4 | import ts2 from "rollup-plugin-typescript2"; 5 | 6 | export default defineConfig({ 7 | plugins: [ 8 | { 9 | ...ts2({ 10 | check: true, 11 | exclude: [ 12 | "**/__tests__/**", 13 | "**/__mocks__/**", 14 | "**/*.test.ts", 15 | "**/*.test.tsx", 16 | "**/*.config.ts", 17 | "**/env.ts", 18 | "**/testing-env/**", 19 | ], 20 | tsconfig: resolve(__dirname, `tsconfig.json`), 21 | tsconfigOverride: { 22 | compilerOptions: { 23 | sourceMap: false, 24 | declaration: true, 25 | declarationMap: true, 26 | }, 27 | }, 28 | }), 29 | enforce: "pre", 30 | }, 31 | ], 32 | build: { 33 | lib: { 34 | entry: resolve(__dirname, "src/index.ts"), 35 | name: "React input mask", 36 | fileName: "index", 37 | }, 38 | rollupOptions: { 39 | external: ["react", "react-dom"], 40 | output: { 41 | globals: { 42 | react: "React", 43 | }, 44 | }, 45 | }, 46 | }, 47 | }); 48 | -------------------------------------------------------------------------------- /src/utils/useRunAfterUpdate.test.ts: -------------------------------------------------------------------------------- 1 | import { renderHook } from "@testing-library/react"; 2 | import { useRunAfterUpdate } from "./useRunAfterUpdate"; 3 | 4 | describe("useRunAfterUpdate", () => { 5 | it("should not run the callback immediately", () => { 6 | const callback = vi.fn(); 7 | renderHook(() => { 8 | const runAfterUpdate = useRunAfterUpdate(); 9 | runAfterUpdate(callback); 10 | }); 11 | expect(callback).toHaveBeenCalled(); 12 | }); 13 | 14 | it("should run the callback after the next paint", () => { 15 | const callback = vi.fn(); 16 | renderHook(() => { 17 | const runAfterUpdate = useRunAfterUpdate(); 18 | runAfterUpdate(() => { 19 | callback(); 20 | }); 21 | }); 22 | expect(callback).toHaveBeenCalled(); 23 | }); 24 | 25 | it("should run multiple callbacks after the next paint", () => { 26 | const callback1 = vi.fn(); 27 | const callback2 = vi.fn(); 28 | renderHook(() => { 29 | const runAfterUpdate = useRunAfterUpdate(); 30 | runAfterUpdate(() => { 31 | callback1(); 32 | 33 | callback2(); 34 | }); 35 | }); 36 | expect(callback1).toHaveBeenCalled(); 37 | expect(callback2).toHaveBeenCalled(); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@code-forge/react-input-mask", 3 | "description": "React input mask used to mask input fields on the fly.", 4 | "author": "Alem Tuzlak", 5 | "version": "1.0.7", 6 | "license": "MIT", 7 | "keywords": [ 8 | "react", 9 | "input", 10 | "mask", 11 | "hook", 12 | "input-mask", 13 | "react-input-mask", 14 | "react-hook", 15 | "react-input-mask-hook" 16 | ], 17 | "private": false, 18 | "type": "module", 19 | "main": "./dist/index.umd.cjs", 20 | "module": "./dist/index.js", 21 | "exports": { 22 | ".": { 23 | "import": "./dist/index.js", 24 | "require": "./dist/index.umd.cjs" 25 | } 26 | }, 27 | "typings": "./dist/index.d.ts", 28 | "files": [ 29 | "dist" 30 | ], 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/Code-Forge-Net/react-input-mask.git" 34 | }, 35 | "bugs": { 36 | "url": "https://github.com/Code-Forge-Net/react-input-mask/issues" 37 | }, 38 | "homepage": "https://github.com/Code-Forge-Net/react-input-mask#readme", 39 | "readme": "https://github.com/Code-Forge-Net/react-input-mask#readme", 40 | "scripts": { 41 | "prepublish": "npm run build", 42 | "dev": "vite --config ./vite.dev.config.ts", 43 | "build": "vite build", 44 | "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0", 45 | "preview": "vite preview", 46 | "test": "vitest run --coverage" 47 | }, 48 | "peerDependencies": { 49 | "react": "^16.8.0 || ^17.0.0 || ^18.0.0", 50 | "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" 51 | }, 52 | "devDependencies": { 53 | "@testing-library/react": "^14.0.0", 54 | "@types/node": "^18.16.0", 55 | "@types/react": "^18.0.28", 56 | "@types/react-dom": "^18.0.11", 57 | "@typescript-eslint/eslint-plugin": "^5.57.1", 58 | "@typescript-eslint/parser": "^5.57.1", 59 | "@vitejs/plugin-react": "^4.0.0-beta.0", 60 | "@vitest/coverage-c8": "^0.30.1", 61 | "eslint": "^8.38.0", 62 | "eslint-plugin-react-hooks": "^4.6.0", 63 | "eslint-plugin-react-refresh": "^0.3.4", 64 | "happy-dom": "^9.9.2", 65 | "react": "^18.2.0", 66 | "react-dom": "^18.2.0", 67 | "react-hook-form": "^7.43.9", 68 | "rollup-plugin-typescript2": "^0.34.1", 69 | "typescript": "^5.0.4", 70 | "vite": "^4.3.0", 71 | "vitest": "^0.30.1" 72 | } 73 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | -------------------------------------------------------------------------------- /src/hook/useInputMask.tsx: -------------------------------------------------------------------------------- 1 | import { useMemo, useState } from "react"; 2 | import type { KeyboardEvent } from "react"; 3 | import { 4 | convertRawValueToMaskedValue, 5 | generateDefaultValues, 6 | isValidInput, 7 | isWholeInputSelected, 8 | triggerInputChange, 9 | useRunAfterUpdate, 10 | } from "../utils"; 11 | 12 | interface UseInputMaskProps { 13 | mask?: string; 14 | placeholderChar?: string; 15 | charRegex?: RegExp; 16 | numRegex?: RegExp; 17 | value?: HTMLInputElement["value"]; 18 | type?: "raw" | "mask"; 19 | } 20 | export const LETTER_REGEX = /^[a-zA-Z]*$/; 21 | export const DIGIT_REGEX = /^[0-9]*$/; 22 | 23 | export function useInputMask({ 24 | mask = "", 25 | placeholderChar = "_", 26 | type = "raw", 27 | value, 28 | charRegex = LETTER_REGEX, 29 | numRegex = DIGIT_REGEX, 30 | }: UseInputMaskProps) { 31 | const maskRegex = /[^A9*]+/g; 32 | const filteredMask = mask?.replace(maskRegex, ""); 33 | const run = useRunAfterUpdate(); 34 | const { maskValue: defaultMask, rawValue: defaultRaw } = useMemo( 35 | () => 36 | generateDefaultValues( 37 | mask, 38 | value, 39 | type, 40 | charRegex, 41 | numRegex, 42 | placeholderChar 43 | ), 44 | [mask, value, type, charRegex, numRegex, placeholderChar] 45 | ); 46 | 47 | const [rawValue, setRawValue] = useState(defaultRaw); 48 | const [maskValue, setMaskValue] = useState(defaultMask); 49 | 50 | const setMaskValues = ( 51 | raw: string, 52 | input: HTMLInputElement, 53 | event: KeyboardEvent 54 | ) => { 55 | setRawValue(raw); 56 | const maskValue = convertRawValueToMaskedValue(raw, mask, placeholderChar); 57 | 58 | setMaskValue(maskValue); 59 | const value = type === "raw" ? raw : maskValue; 60 | // Calls react onChange event 61 | triggerInputChange(event.target as HTMLInputElement, value); 62 | // sets the caret position to the next available position 63 | run(() => { 64 | const caretPosition = maskValue.indexOf(placeholderChar); 65 | input.setSelectionRange(caretPosition, caretPosition); 66 | }); 67 | }; 68 | 69 | const onKeyDown = (event: KeyboardEvent) => { 70 | const value = event.key; 71 | const input = event.target as HTMLInputElement; 72 | const currentMaskIndex = rawValue.length; 73 | const currentMaskChar = filteredMask[currentMaskIndex]; 74 | // Select whole input if user presses Ctrl+A 75 | if (event.ctrlKey && event.key.toLowerCase() === "a") { 76 | event.preventDefault(); 77 | input.setSelectionRange(0, mask.length); 78 | return; 79 | } 80 | if (value === "Tab" || value === "Enter") { 81 | return; 82 | } 83 | 84 | event.preventDefault(); 85 | 86 | if (value === "Backspace" && rawValue.length > 0) { 87 | const isWholeSelected = isWholeInputSelected(input, mask); 88 | const newValue = isWholeSelected ? "" : rawValue.slice(0, -1); 89 | return setMaskValues(newValue, input, event); 90 | } 91 | 92 | const isValid = isValidInput({ 93 | value, 94 | currentMaskChar, 95 | charRegex, 96 | numRegex, 97 | filteredMask, 98 | rawValue, 99 | }); 100 | 101 | if (!isValid) { 102 | return; 103 | } 104 | 105 | const newValue = rawValue + value; 106 | setMaskValues(newValue, input, event); 107 | }; 108 | 109 | const getInputProps = () => { 110 | if (!mask) return {}; 111 | return { 112 | value: maskValue, 113 | onKeyDown, 114 | }; 115 | }; 116 | 117 | return { getInputProps }; 118 | } 119 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | import { LETTER_REGEX, DIGIT_REGEX } from "../hook/useInputMask"; 2 | 3 | export const isLetter = (char: string, regex = LETTER_REGEX) => 4 | regex.test(char); 5 | export const isDigit = (char: string, regex = DIGIT_REGEX) => regex.test(char); 6 | export const isWildcard = (char: string) => char === "*"; 7 | export const isMaskChar = (char: string) => 8 | char === "A" || char === "9" || char === "*"; 9 | 10 | export const getMaskedValueFromRaw = (mask: string, rawValue: string) => { 11 | let reachedIndex = 0; 12 | const output = mask 13 | .split("") 14 | .map((char) => { 15 | if (!isMaskChar(char)) return char; 16 | const returnValue = rawValue[reachedIndex]; 17 | if (!returnValue) return char; 18 | 19 | if (char === "*") { 20 | reachedIndex += 1; 21 | return returnValue; 22 | } 23 | if (char === "A" && isLetter(rawValue[reachedIndex])) { 24 | reachedIndex += 1; 25 | return returnValue; 26 | } 27 | if (char === "9" && isDigit(rawValue[reachedIndex])) { 28 | reachedIndex += 1; 29 | return returnValue; 30 | } 31 | return char; 32 | }) 33 | .join(""); 34 | 35 | return output; 36 | }; 37 | 38 | export const convertMaskToPlaceholder = ( 39 | mask: string, 40 | placeholderChar: string, 41 | reachedIndex = 0 42 | ) => { 43 | return ( 44 | mask.slice(0, reachedIndex) + 45 | mask 46 | .slice(reachedIndex, mask.length) 47 | .replaceAll("*", placeholderChar) 48 | .replaceAll("A", placeholderChar) 49 | .replaceAll("9", placeholderChar) 50 | ); 51 | }; 52 | /** 53 | * Goes through the mask until it reaches the raw value length and returns the count of non-masked characters 54 | * @param mask Mask string 55 | * @param rawLength Length of the raw value 56 | * @returns Returns the count of non-masked characters 57 | */ 58 | export const getNonMaskedCharCount = (mask: string, rawLength: number) => { 59 | let reachedIndex = 0; 60 | return mask.split("").filter((char) => { 61 | if (reachedIndex >= rawLength) return false; 62 | if (isMaskChar(char)) { 63 | reachedIndex += 1; 64 | return false; 65 | } 66 | return true; 67 | }).length; 68 | }; 69 | 70 | export const convertRawValueToMaskedValue = ( 71 | rawValue: string, 72 | mask: string, 73 | placeholderChar: string 74 | ) => { 75 | const output = getMaskedValueFromRaw(mask, rawValue); 76 | const extraChars = getNonMaskedCharCount(mask, rawValue.length); 77 | return convertMaskToPlaceholder( 78 | output, 79 | placeholderChar, 80 | rawValue.length + extraChars 81 | ); 82 | }; 83 | interface IsValidInputProps { 84 | value: string; 85 | currentMaskChar: string; 86 | filteredMask: string; 87 | rawValue: string; 88 | charRegex: RegExp; 89 | numRegex: RegExp; 90 | } 91 | export const isValidInput = ({ 92 | filteredMask, 93 | value, 94 | rawValue, 95 | currentMaskChar, 96 | charRegex, 97 | numRegex, 98 | }: IsValidInputProps) => { 99 | if (value.length > 1) { 100 | return false; 101 | } 102 | if (filteredMask.length === rawValue.length) { 103 | return false; 104 | } 105 | 106 | return maskAndValueMatch(value, currentMaskChar, charRegex, numRegex); 107 | }; 108 | 109 | export const maskAndValueMatch = ( 110 | value: string, 111 | currentMaskChar: string, 112 | charRegex: RegExp, 113 | numRegex: RegExp 114 | ) => { 115 | if (isLetter(value, charRegex) && isLetter(currentMaskChar, charRegex)) { 116 | return true; 117 | } 118 | if (isDigit(value, numRegex) && isDigit(currentMaskChar, numRegex)) { 119 | return true; 120 | } 121 | if (isWildcard(currentMaskChar)) { 122 | return true; 123 | } 124 | return false; 125 | }; 126 | 127 | export const isWholeInputSelected = (input: HTMLInputElement, mask: string) => { 128 | return input.selectionStart === 0 && input.selectionEnd === mask.length; 129 | }; 130 | 131 | export const triggerInputChange = ( 132 | node: HTMLInputElement, 133 | inputValue: string 134 | ) => { 135 | node.value = inputValue; 136 | if (typeof document === "undefined") return; 137 | const e = document.createEvent("HTMLEvents"); 138 | e.initEvent("change", true, false); 139 | node.dispatchEvent(e); 140 | }; 141 | export * from "./useRunAfterUpdate"; 142 | 143 | export const generateRawValue = ( 144 | mask = "", 145 | value = "", 146 | charRegex: RegExp, 147 | numRegex: RegExp, 148 | placeholderChar: string 149 | ) => { 150 | const defaultReturn = { 151 | maskValue: convertMaskToPlaceholder(mask, placeholderChar), 152 | rawValue: "", 153 | }; 154 | if (!mask || !value) { 155 | return defaultReturn; 156 | } 157 | const filteredMask = mask.replace(/[^A9*]+/g, ""); 158 | const chars = value.split(""); 159 | const allValid = chars.every((char, index) => 160 | isValidInput({ 161 | value: char, 162 | currentMaskChar: filteredMask[index], 163 | charRegex, 164 | numRegex, 165 | filteredMask, 166 | rawValue: value.slice(0, index), 167 | }) 168 | ); 169 | 170 | if (allValid) { 171 | return { 172 | maskValue: convertRawValueToMaskedValue(value, mask, placeholderChar), 173 | rawValue: value, 174 | }; 175 | } 176 | 177 | return defaultReturn; 178 | }; 179 | 180 | export const generateMaskValue = ( 181 | mask: string, 182 | value: string, 183 | charRegex: RegExp, 184 | numRegex: RegExp, 185 | placeholderChar: string 186 | ) => { 187 | const defaultReturn = { 188 | maskValue: convertMaskToPlaceholder(mask, placeholderChar), 189 | rawValue: "", 190 | }; 191 | if (value.length != mask.length) { 192 | return defaultReturn; 193 | } 194 | const chars = mask.split(""); 195 | const valid = chars.every((char, index) => { 196 | if (!isMaskChar(char)) { 197 | return char === value[index]; 198 | } 199 | return maskAndValueMatch(value[index], char, charRegex, numRegex); 200 | }); 201 | if (valid) { 202 | const rawValue = chars 203 | .map((char, index) => { 204 | if (isMaskChar(char)) { 205 | return value[index]; 206 | } 207 | return ""; 208 | }) 209 | .join(""); 210 | return { maskValue: value, rawValue }; 211 | } 212 | return defaultReturn; 213 | }; 214 | export const generateDefaultValues = ( 215 | mask = "", 216 | value = "", 217 | type: "raw" | "mask", 218 | charRegex: RegExp, 219 | numRegex: RegExp, 220 | placeholderChar: string 221 | ) => { 222 | if (type === "mask") { 223 | return generateMaskValue(mask, value, charRegex, numRegex, placeholderChar); 224 | } 225 | return generateRawValue(mask, value, charRegex, numRegex, placeholderChar); 226 | }; 227 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Input Mask 2 | ![GitHub Repo stars](https://img.shields.io/github/stars/Code-Forge-Net/react-input-mask?style=social) 3 | ![npm](https://img.shields.io/npm/v/@code-forge/react-input-mask?style=plastic) 4 | ![GitHub](https://img.shields.io/github/license/Code-Forge-Net/react-input-mask?style=plastic) 5 | ![npm](https://img.shields.io/npm/dy/@code-forge/react-input-mask?style=plastic) 6 | ![GitHub issues](https://img.shields.io/github/issues/Code-Forge-Net/react-input-mask?style=plastic) 7 | ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/Code-Forge-Net/react-input-mask?style=plastic) 8 | ![GitHub last commit](https://img.shields.io/github/last-commit/Code-Forge-Net/react-input-mask?style=plastic) 9 | ![GitHub top language](https://img.shields.io/github/languages/top/Code-Forge-Net/react-input-mask?style=plastic) 10 | 11 | React Input Mask is an open source library for React that provides an easy way to apply masks to input fields. 12 | 13 | Masks can be used to enforce specific formatting for user input, such as phone numbers, social security numbers, and credit card numbers. With React Input Mask, you can define a mask for your input field, and the library will automatically format the user's input according to the specified mask. 14 | 15 | ## Why React Input Mask? 16 | 17 | React Input Mask is a lightweight library that provides a simple API for applying masks to input fields. It is built on top of React Hooks, and is designed to be used with functional components. It is also compatible with libraries such as react-hook-form. 18 | The design philosophy behind React Input Mask is to provide a simple API that is easy to use and understand via a hook instead of 19 | a component. 20 | 21 | It is also designed to be used with Next.js and Remix.run and other server-side rendering frameworks. 22 | 23 | ## Installation 24 | React Input Mask can be installed via npm or yarn: 25 | 26 | 27 | `npm install @code-forge/react-input-mask` 28 | 29 | 30 | `yarn add @code-forge/react-input-mask` 31 | 32 | ## Usage 33 | Using React Input Mask is easy. Simply import the useInputMask hook from the library, and pass the mask prop to the hook. The hook will return an object containing the value and onMouseDown props that you can pass to your input field. 34 | 35 | ```jsx 36 | import React from 'react'; 37 | import { useInputMask } from '@code-forge/react-input-mask'; 38 | 39 | const MyComponent = () => { 40 | const { getInputProps } = useInputMask({ mask: 'One does not simply walk into AAAAAA' }); 41 | return ( 42 | { 43 | // Your onChange handler gets the output of the hook (won't trigger if the input is invalid) 44 | console.log(e.target.value); 45 | }} /> 46 | ); 47 | }; 48 | ``` 49 | 50 | 51 | In the example above, we've applied a mask to fill the word needed to complete the sentence. 52 | 53 | You can customize the mask to fit your needs by using a variety of special characters that represent different types of input. 54 | 55 | | Character | Description | 56 | |-----------|-------------| 57 | | 9 | Represents a number.| 58 | | A | Represents a letter. | 59 | | * | Represents a wildcard. | 60 | 61 | ## Available Props 62 | 63 | | Prop | Type | Description | Default | 64 | |------|------|-------------|---------| 65 | | mask | string | The mask to apply to the input field. | undefined | 66 | | placeholderChar | string | The character to use as a placeholder for the mask characters (eg. 999-999 with placeholderChar set to "@" will produce @@@-@@@). | "_" | 67 | | charRegex | RegExp | A regular expression that represents the characters that are allowed to be entered into the input field. | /^[a-zA-Z]*$/| 68 | | numRegex | RegExp | A regular expression that represents the numbers that are allowed to be entered into the input field. | /^[0-9]*$/ | 69 | | type | "raw" or "mask" | The type of value to return from the hook. If set to "raw", the hook will return the raw value of the input field (eg. mask 999-999-99 with 111-111-11 will output 11111111). If set to "mask", the hook will return the masked value of the input field. (eg. mask 999-999-99 with 111-111-11 will output 111-111-11) | "raw" | 70 | | value | string | The initial value of the input field. (The hook expects to be given a value created by itself, if you provide an invalid value it will try to fill as much of the mask as it can but relies on you to pass it a positive value, otherwise it will default to its default values) | undefined | 71 | 72 | ## Examples 73 | 74 | ### Phone Number 75 | ```jsx 76 | import React from 'react'; 77 | import { useInputMask } from '@code-forge/react-input-mask'; 78 | 79 | const MyComponent = () => { 80 | const { getInputProps } = useInputMask({ mask: '+(999) 999-9999' }); 81 | return ( 82 | 83 | ); 84 | }; 85 | ``` 86 | 87 | ### Social Security Number 88 | ```jsx 89 | import React from 'react'; 90 | import { useInputMask } from '@code-forge/react-input-mask'; 91 | 92 | const MyComponent = () => { 93 | const { getInputProps } = useInputMask({ mask: '999-99-9999' }); 94 | return ( 95 | 96 | ); 97 | }; 98 | ``` 99 | 100 | ### Credit Card Number 101 | ```jsx 102 | import React from 'react'; 103 | import { useInputMask } from '@code-forge/react-input-mask'; 104 | 105 | const MyComponent = () => { 106 | const { getInputProps } = useInputMask({ mask: '9999 9999 9999 9999' }); 107 | return ( 108 | 109 | ); 110 | }; 111 | ``` 112 | 113 | ### Handle keyDown before the mask 114 | ```jsx 115 | import React from 'react'; 116 | import { useInputMask } from '@code-forge/react-input-mask'; 117 | 118 | const MyComponent = () => { 119 | const { getInputProps } = useInputMask({ mask: '9999 9999 9999 9999' }); 120 | const maskProps = getInputProps(); 121 | return ( 122 | { 123 | // do something 124 | maskProps.onKeyDown(e); 125 | }} value={maskProps.value} /> 126 | ); 127 | }; 128 | ``` 129 | 130 | ### Usage with react-hook-form 131 | 132 | ```jsx 133 | import React from 'react'; 134 | import { useForm } from 'react-hook-form'; 135 | import { useInputMask } from '@code-forge/react-input-mask'; 136 | 137 | const MyComponent = () => { 138 | const { register, handleSubmit } = useForm(); 139 | const { getInputProps } = useInputMask({ mask: '9999 9999 9999 9999' }); 140 | return ( 141 |
console.log(data))}> 142 | 143 | 144 |
145 | ); 146 | }; 147 | ``` 148 | ## Support 149 | 150 | If you like the project, please consider supporting us by giving a ⭐️ on Github. 151 | 152 | ## License 153 | 154 | MIT 155 | 156 | ## Bugs 157 | 158 | If you find a bug, please file an issue on [our issue tracker on GitHub](https://github.com/Code-Forge-Net/react-input-mask/issues) 159 | 160 | 161 | ## Contributing 162 | 163 | Thank you for considering contributing to @code-forge/react-input-mask! We welcome any contributions, big or small, including bug reports, feature requests, documentation improvements, or code changes. 164 | 165 | To get started, please fork this repository and make your changes in a new branch. Once you're ready to submit your changes, please open a pull request with a clear description of your changes and any related issues or pull requests. 166 | 167 | Please note that all contributions are subject to our [Code of Conduct](https://github.com/Code-Forge-Net/react-input-mask/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. 168 | 169 | We appreciate your time and effort in contributing to react-input-mask and helping to make it a better tool for the community! 170 | -------------------------------------------------------------------------------- /src/hook/useInputMask.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { act, fireEvent, render, renderHook } from "@testing-library/react"; 3 | import { useInputMask } from "./useInputMask"; 4 | 5 | const renderComponent = ( 6 | props: Parameters[0], 7 | onChange: () => void = () => {} 8 | ) => { 9 | const Component = () => { 10 | const { getInputProps } = useInputMask(props); 11 | return ( 12 | 13 | ); 14 | }; 15 | return render(); 16 | }; 17 | 18 | describe("useInputMask", () => { 19 | it("renders correctly", () => { 20 | const { result } = renderHook(() => useInputMask({ mask: "AAA-999" })); 21 | expect(result.current.getInputProps()).toMatchObject({ value: "___-___" }); 22 | }); 23 | 24 | it("updates letter value on input when valid", () => { 25 | const { getByTestId } = renderComponent({ mask: "AAA-999", type: "raw" }); 26 | 27 | const input = getByTestId("input"); 28 | 29 | act(() => { 30 | fireEvent.keyDown(input, { key: "a", target: { value: "a" } }); 31 | }); 32 | expect(input.getAttribute("value")).toBe("a__-___"); 33 | }); 34 | it("updates letter value on input when valid and is A", () => { 35 | const { getByTestId } = renderComponent({ mask: "AAA-999", type: "raw" }); 36 | 37 | const input = getByTestId("input"); 38 | 39 | act(() => { 40 | fireEvent.keyDown(input, { key: "A", target: { value: "A" } }); 41 | }); 42 | expect(input.getAttribute("value")).toBe("A__-___"); 43 | }); 44 | 45 | it("nothing happens when letter is next and number entered", () => { 46 | const { getByTestId } = renderComponent({ mask: "AAA-999", type: "raw" }); 47 | 48 | const input = getByTestId("input"); 49 | 50 | act(() => { 51 | fireEvent.keyDown(input, { key: "8", target: { value: "8" } }); 52 | }); 53 | expect(input.getAttribute("value")).toBe("___-___"); 54 | }); 55 | 56 | it("nothing happens when letter is next and special char entered", () => { 57 | const { getByTestId } = renderComponent({ mask: "AAA-999", type: "raw" }); 58 | 59 | const input = getByTestId("input"); 60 | 61 | act(() => { 62 | fireEvent.keyDown(input, { key: "*" }); 63 | }); 64 | expect(input.getAttribute("value")).toBe("___-___"); 65 | }); 66 | 67 | it("when number entered and number is next it updates value", () => { 68 | const { getByTestId } = renderComponent({ mask: "9AA-999", type: "raw" }); 69 | 70 | const input = getByTestId("input"); 71 | 72 | act(() => { 73 | fireEvent.keyDown(input, { key: "1" }); 74 | }); 75 | expect(input.getAttribute("value")).toBe("1__-___"); 76 | }); 77 | 78 | it("when letter entered and number is next it does not update the value", () => { 79 | const { getByTestId } = renderComponent({ mask: "9AA-999", type: "raw" }); 80 | const input = getByTestId("input"); 81 | 82 | act(() => { 83 | fireEvent.keyDown(input, { key: "a" }); 84 | }); 85 | expect(input.getAttribute("value")).toBe("___-___"); 86 | }); 87 | 88 | it("when special char entered and number is next it does not update the value", () => { 89 | const { getByTestId } = renderComponent({ mask: "9AA-999", type: "raw" }); 90 | const input = getByTestId("input"); 91 | 92 | act(() => { 93 | fireEvent.keyDown(input, { key: "*" }); 94 | }); 95 | expect(input.getAttribute("value")).toBe("___-___"); 96 | }); 97 | 98 | it("when special char entered and wildcard is next value updated", () => { 99 | const { getByTestId } = renderComponent({ mask: "*AA-999", type: "raw" }); 100 | const input = getByTestId("input"); 101 | 102 | act(() => { 103 | fireEvent.keyDown(input, { key: "*" }); 104 | }); 105 | expect(input.getAttribute("value")).toBe("*__-___"); 106 | }); 107 | 108 | it("when letter entered and wildcard is next value updated", () => { 109 | const { getByTestId } = renderComponent({ mask: "*AA-999", type: "raw" }); 110 | const input = getByTestId("input"); 111 | 112 | act(() => { 113 | fireEvent.keyDown(input, { key: "A" }); 114 | }); 115 | expect(input.getAttribute("value")).toBe("A__-___"); 116 | }); 117 | it("when number entered and wildcard is next value updated", () => { 118 | const { getByTestId } = renderComponent({ mask: "*AA-999", type: "raw" }); 119 | const input = getByTestId("input"); 120 | 121 | act(() => { 122 | fireEvent.keyDown(input, { key: "2" }); 123 | }); 124 | expect(input.getAttribute("value")).toBe("2__-___"); 125 | }); 126 | 127 | it("when backspace is clicked it deletes a character", () => { 128 | const { getByTestId } = renderComponent({ mask: "*AA-999", type: "raw" }); 129 | const input = getByTestId("input"); 130 | 131 | act(() => { 132 | fireEvent.keyDown(input, { key: "Backspace" }); 133 | }); 134 | expect(input.getAttribute("value")).toBe("___-___"); 135 | }); 136 | 137 | it("deleting over non mask values works correctly", () => { 138 | const { getByTestId } = renderComponent({ 139 | mask: "9999 9999 9999 9999", 140 | type: "raw", 141 | value: "9999999999999999", 142 | }); 143 | for (let i = 0; i < 9; i++) { 144 | act(() => { 145 | fireEvent.keyDown(getByTestId("input"), { key: "Backspace" }); 146 | }); 147 | } 148 | expect(getByTestId("input").getAttribute("value")).toBe( 149 | "9999 999_ ____ ____" 150 | ); 151 | }); 152 | 153 | it("entering values when mask complete does not work", () => { 154 | const { getByTestId } = renderComponent({ 155 | mask: "9999 9999 9999 9999", 156 | type: "raw", 157 | value: "9999999999999999", 158 | }); 159 | act(() => { 160 | fireEvent.keyDown(getByTestId("input"), { key: "1" }); 161 | }); 162 | expect(getByTestId("input").getAttribute("value")).toBe( 163 | "9999 9999 9999 9999" 164 | ); 165 | }); 166 | 167 | it("entering values when mask complete and it is a special key with multiple letters doesn't work", () => { 168 | const { getByTestId } = renderComponent({ 169 | mask: "9999 9999 9999 9999", 170 | type: "raw", 171 | value: "9999999999999999", 172 | }); 173 | act(() => { 174 | fireEvent.keyDown(getByTestId("input"), { key: "Capital" }); 175 | }); 176 | expect(getByTestId("input").getAttribute("value")).toBe( 177 | "9999 9999 9999 9999" 178 | ); 179 | }); 180 | 181 | it("entering values with multiple characters does not work", () => { 182 | const { getByTestId } = renderComponent({ 183 | mask: "AAAAAAAAAAAAA", 184 | type: "raw", 185 | value: "", 186 | }); 187 | act(() => { 188 | fireEvent.keyDown(getByTestId("input"), { key: "Capital" }); 189 | }); 190 | expect(getByTestId("input").getAttribute("value")).toBe("_____________"); 191 | }); 192 | 193 | it("when CTRL + A is clicked then backspace everything is deleted", () => { 194 | const { getByTestId } = renderComponent({ 195 | mask: "*AA-999", 196 | type: "raw", 197 | value: "2AA123", 198 | }); 199 | 200 | const input = getByTestId("input"); 201 | 202 | act(() => { 203 | fireEvent.keyDown(input, { key: "A", ctrlKey: true }); 204 | fireEvent.keyDown(input, { key: "Backspace" }); 205 | }); 206 | expect(input.getAttribute("value")).toBe("___-___"); 207 | }); 208 | 209 | it("when a full valid mask is provided in raw mode it is displayed and saved correctly", () => { 210 | const { getByTestId } = renderComponent({ 211 | mask: "*AA-999", 212 | type: "raw", 213 | value: "2AA123", 214 | }); 215 | 216 | const input = getByTestId("input"); 217 | expect(input.getAttribute("value")).toBe("2AA-123"); 218 | }); 219 | 220 | it("when a partial valid mask is provided in raw mode it is displayed and saved correctly", () => { 221 | const { getByTestId } = renderComponent({ 222 | mask: "*AA-999", 223 | type: "raw", 224 | value: "2AA", 225 | }); 226 | 227 | const input = getByTestId("input"); 228 | expect(input.getAttribute("value")).toBe("2AA-___"); 229 | }); 230 | 231 | it("when a full valid mask is provided in mask mode it is displayed and saved correctly", () => { 232 | const { getByTestId } = renderComponent({ 233 | mask: "*AA-999", 234 | type: "mask", 235 | value: "2AA-123", 236 | }); 237 | 238 | const input = getByTestId("input"); 239 | expect(input.getAttribute("value")).toBe("2AA-123"); 240 | }); 241 | /* 242 | it("when a partial valid mask is provided in mask mode it is displayed and saved correctly", () => { 243 | const { getByTestId } = renderComponent({ 244 | mask: "*AA-999", 245 | type: "mask", 246 | value: "2AA-2", 247 | }); 248 | 249 | const input = getByTestId("input"); 250 | expect(input.getAttribute("value")).toBe("2AA-2__"); 251 | }); */ 252 | 253 | it("when you Tab out the element loses focus", () => { 254 | const { getByTestId } = renderComponent({ 255 | mask: "*AA-999", 256 | type: "raw", 257 | value: "2AA123", 258 | }); 259 | const input = getByTestId("input"); 260 | 261 | act(() => { 262 | fireEvent.keyDown(input, { key: "Tab" }); 263 | }); 264 | expect(document.activeElement).not.toBe(input); 265 | }); 266 | 267 | it("when mask not provided value is not set", () => { 268 | const { getByTestId } = renderComponent({ 269 | type: "raw", 270 | value: "2AA123", 271 | }); 272 | const input = getByTestId("input"); 273 | expect(input.getAttribute("value")).toBe(null); 274 | }); 275 | }); 276 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | "lib": ["dom", "dom.iterable", "esnext"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | "jsx": "react", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | /* Modules */ 26 | "module": "ES2020", /* Specify what module code is generated. */ 27 | "rootDir": "./src", /* Specify the root folder within your source files. */ 28 | "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 29 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 30 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 31 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 32 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 33 | "types": ["vitest/globals"], /* Specify type package names to be included without being referenced in a source file. */ 34 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 35 | // "resolveJsonModule": true, /* Enable importing .json files */ 36 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 37 | 38 | /* JavaScript Support */ 39 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 40 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 41 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 42 | 43 | /* Emit */ 44 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 45 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 46 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 47 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 48 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 49 | "outDir": "./dist", /* Specify an output folder for all emitted files. */ 50 | // "removeComments": true, /* Disable emitting comments. */ 51 | // "noEmit": true, /* Disable emitting files from a compilation. */ 52 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 53 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 54 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 55 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 56 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 57 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 58 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 59 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 60 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 61 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 62 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 63 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 64 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 65 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 66 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 67 | 68 | /* Interop Constraints */ 69 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 70 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 71 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 72 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 73 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 74 | 75 | /* Type Checking */ 76 | "strict": true, /* Enable all strict type-checking options. */ 77 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 78 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 79 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 80 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 81 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 82 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 83 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 84 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 85 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 86 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 87 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 88 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 89 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 90 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 91 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 92 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 93 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 94 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 95 | 96 | /* Completeness */ 97 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 98 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 99 | }, 100 | "exclude": [ 101 | "./bin/**/*.test.ts", 102 | "./dist/**/*", 103 | "./bin/mocks/**/*", 104 | "./*.config.ts", 105 | ] 106 | } -------------------------------------------------------------------------------- /src/utils/index.test.ts: -------------------------------------------------------------------------------- 1 | import { DIGIT_REGEX, LETTER_REGEX } from "../hook/useInputMask"; 2 | import { 3 | isLetter, 4 | isDigit, 5 | isWildcard, 6 | getMaskedValueFromRaw, 7 | convertMaskToPlaceholder, 8 | convertRawValueToMaskedValue, 9 | isValidInput, 10 | isWholeInputSelected, 11 | getNonMaskedCharCount, 12 | generateMaskValue, 13 | maskAndValueMatch, 14 | generateRawValue, 15 | isMaskChar, 16 | generateDefaultValues, 17 | triggerInputChange, 18 | } from "./"; 19 | 20 | describe("isLetter", () => { 21 | test("returns true for valid letters", () => { 22 | expect(isLetter("a")).toBe(true); 23 | expect(isLetter("A")).toBe(true); 24 | expect(isLetter("z")).toBe(true); 25 | expect(isLetter("Z")).toBe(true); 26 | }); 27 | 28 | test("returns false for non-letter characters", () => { 29 | expect(isLetter("1")).toBe(false); 30 | expect(isLetter("*")).toBe(false); 31 | expect(isLetter(" ")).toBe(false); 32 | }); 33 | }); 34 | 35 | describe("isDigit", () => { 36 | test("returns true for valid digits", () => { 37 | expect(isDigit("0")).toBe(true); 38 | expect(isDigit("1")).toBe(true); 39 | expect(isDigit("9")).toBe(true); 40 | }); 41 | 42 | test("returns false for non-digit characters", () => { 43 | expect(isDigit("a")).toBe(false); 44 | expect(isDigit("*")).toBe(false); 45 | expect(isDigit(" ")).toBe(false); 46 | }); 47 | }); 48 | 49 | describe("isWildcard", () => { 50 | test("returns true for wildcard character", () => { 51 | expect(isWildcard("*")).toBe(true); 52 | }); 53 | 54 | test("returns false for non-wildcard characters", () => { 55 | expect(isWildcard("a")).toBe(false); 56 | expect(isWildcard("1")).toBe(false); 57 | expect(isWildcard(" ")).toBe(false); 58 | }); 59 | }); 60 | 61 | describe("maskAndValueMatch", () => { 62 | const charRegex = LETTER_REGEX; 63 | const numRegex = DIGIT_REGEX; 64 | 65 | test("returns true for matching letter and letter mask char", () => { 66 | expect(maskAndValueMatch("a", "A", charRegex, numRegex)).toBe(true); 67 | expect(maskAndValueMatch("z", "A", charRegex, numRegex)).toBe(true); 68 | expect(maskAndValueMatch("B", "A", charRegex, numRegex)).toBe(true); 69 | }); 70 | 71 | test("returns true for matching digit and digit mask char", () => { 72 | expect(maskAndValueMatch("1", "9", charRegex, numRegex)).toBe(true); 73 | expect(maskAndValueMatch("5", "9", charRegex, numRegex)).toBe(true); 74 | expect(maskAndValueMatch("0", "9", charRegex, numRegex)).toBe(true); 75 | }); 76 | 77 | test("returns true for wildcard mask char", () => { 78 | expect(maskAndValueMatch("a", "*", charRegex, numRegex)).toBe(true); 79 | expect(maskAndValueMatch("5", "*", charRegex, numRegex)).toBe(true); 80 | expect(maskAndValueMatch("!", "*", charRegex, numRegex)).toBe(true); 81 | }); 82 | 83 | test("returns false for non-matching value and mask char", () => { 84 | expect(maskAndValueMatch("a", "9", charRegex, numRegex)).toBe(false); 85 | expect(maskAndValueMatch("1", "A", charRegex, numRegex)).toBe(false); 86 | expect(maskAndValueMatch("&", "9", charRegex, numRegex)).toBe(false); 87 | }); 88 | }); 89 | 90 | describe("getMaskedValueFromRaw", () => { 91 | test("returns the correct output for a simple mask and raw value", () => { 92 | expect(getMaskedValueFromRaw("***-***", "abc123")).toBe("abc-123"); 93 | }); 94 | 95 | test("returns the correct output when the mask and raw value have the same length", () => { 96 | expect(getMaskedValueFromRaw("AAA-999", "abc123")).toBe("abc-123"); 97 | }); 98 | 99 | test("returns the correct output when the raw value is shorter than the mask", () => { 100 | expect(getMaskedValueFromRaw("AAA-999", "ab")).toBe("abA-999"); 101 | }); 102 | 103 | test("returns the correct output when the raw value is longer than the mask", () => { 104 | expect(getMaskedValueFromRaw("AAA-999", "abcdefghi")).toBe("abc-999"); 105 | }); 106 | 107 | test("returns the correct output when the raw value contains non-letter and non-digit characters", () => { 108 | expect(getMaskedValueFromRaw("A9A-9A9", "a!b@c#")).toBe("a9A-9A9"); 109 | }); 110 | 111 | test("returns the correct output when the mask contains only wildcards", () => { 112 | expect(getMaskedValueFromRaw("***", "abc123")).toBe("abc"); 113 | }); 114 | 115 | test("returns the correct output when the mask and raw value contain only one type of character", () => { 116 | expect(getMaskedValueFromRaw("AAA", "abc")).toBe("abc"); 117 | expect(getMaskedValueFromRaw("999", "123")).toBe("123"); 118 | expect(getMaskedValueFromRaw("***", "abc")).toBe("abc"); 119 | }); 120 | 121 | test("returns the correct output when the raw value is empty", () => { 122 | expect(getMaskedValueFromRaw("AAA-999", "")).toBe("AAA-999"); 123 | }); 124 | 125 | test("returns the correct output when the mask is empty", () => { 126 | expect(getMaskedValueFromRaw("", "abc123")).toBe(""); 127 | }); 128 | }); 129 | 130 | describe("convertMaskToPlaceholder", () => { 131 | test("returns an empty string if the input mask is an empty string", () => { 132 | expect(convertMaskToPlaceholder("", "-")).toBe(""); 133 | }); 134 | 135 | test("replaces all '*' characters in the mask with the placeholder character", () => { 136 | expect(convertMaskToPlaceholder("***", "-")).toBe("---"); 137 | expect(convertMaskToPlaceholder("*A*B*C*", "-")).toBe("---B-C-"); 138 | expect(convertMaskToPlaceholder("*", "-")).toBe("-"); 139 | }); 140 | 141 | test("replaces all 'A' characters in the mask with the placeholder character", () => { 142 | expect(convertMaskToPlaceholder("AAA", "-")).toBe("---"); 143 | expect(convertMaskToPlaceholder("A*A*A", "-")).toBe("-----"); 144 | expect(convertMaskToPlaceholder("A", "-")).toBe("-"); 145 | }); 146 | 147 | test("replaces all '9' characters in the mask with the placeholder character", () => { 148 | expect(convertMaskToPlaceholder("999", "-")).toBe("---"); 149 | expect(convertMaskToPlaceholder("9*9*9", "-")).toBe("-----"); 150 | expect(convertMaskToPlaceholder("9", "-")).toBe("-"); 151 | }); 152 | 153 | test("replaces all '*' and 'A' and '9' characters in the mask with the placeholder character", () => { 154 | expect(convertMaskToPlaceholder("*A9", "-")).toBe("---"); 155 | expect(convertMaskToPlaceholder("*A9B*C*D*9A", "-")).toBe("---B-C-D---"); 156 | expect(convertMaskToPlaceholder("A99**", "-")).toBe("-----"); 157 | }); 158 | 159 | test("returns the same string if the mask doesn't contain '*' or 'A' or '9' characters", () => { 160 | expect(convertMaskToPlaceholder("abc123", "-")).toBe("abc123"); 161 | expect(convertMaskToPlaceholder("-", "-")).toBe("-"); 162 | expect(convertMaskToPlaceholder(" ", "-")).toBe(" "); 163 | }); 164 | 165 | test("replaces all '*' and 'A' and '9' characters in the mask with the provided placeholder character", () => { 166 | expect(convertMaskToPlaceholder("**A9*", "#")).toBe("#####"); 167 | expect(convertMaskToPlaceholder("*A*B*C*", "@")).toBe("@@@B@C@"); 168 | expect(convertMaskToPlaceholder("A999B", "$")).toBe("$$$$B"); 169 | }); 170 | }); 171 | 172 | describe("convertRawValueToMaskedValue", () => { 173 | test("returns an empty string if the input raw value and mask are both empty strings", () => { 174 | expect(convertRawValueToMaskedValue("", "", "-")).toBe(""); 175 | }); 176 | 177 | test("returns the masked value if the input raw value is an empty string", () => { 178 | expect(convertRawValueToMaskedValue("", "A9A-9A9", "-")).toBe("-------"); 179 | expect(convertRawValueToMaskedValue("", "***", "-")).toBe("---"); 180 | expect(convertRawValueToMaskedValue("", "ABC", "-")).toBe("-BC"); 181 | }); 182 | 183 | test("returns the masked value with placeholders for each character in the input raw value", () => { 184 | expect(convertRawValueToMaskedValue("B2C3A3", "A9A-9A9", "-")).toBe( 185 | "B2C-3A3" 186 | ); 187 | expect(convertRawValueToMaskedValue("abc1", "***-9A9", "-")).toBe( 188 | "abc-1--" 189 | ); 190 | expect(convertRawValueToMaskedValue("AAA", "A*A*A", "-")).toBe("AAA--"); 191 | }); 192 | 193 | test("replaces all '*' and 'A' and '9' characters in the mask with the provided placeholder character", () => { 194 | expect( 195 | convertRawValueToMaskedValue("123456789", "999-999-999-9", "#") 196 | ).toBe("123-456-789-#"); 197 | expect(convertRawValueToMaskedValue("abc123", "***-9999", "@")).toBe( 198 | "abc-123@" 199 | ); 200 | expect(convertRawValueToMaskedValue("123", "****A", "$")).toBe("123$$"); 201 | }); 202 | 203 | test("handles edge cases", () => { 204 | expect(convertRawValueToMaskedValue("a", "A", "-")).toBe("a"); 205 | expect(convertRawValueToMaskedValue("1", "9", "-")).toBe("1"); 206 | expect(convertRawValueToMaskedValue("*", "*", "-")).toBe("*"); 207 | }); 208 | }); 209 | 210 | describe("isValidInput", () => { 211 | const charRegex = LETTER_REGEX; 212 | const numRegex = DIGIT_REGEX; 213 | 214 | it("should return false if value has length greater than 1", () => { 215 | const result = isValidInput({ 216 | value: "abc", 217 | currentMaskChar: "A", 218 | filteredMask: "AAA", 219 | rawValue: "a", 220 | charRegex, 221 | numRegex, 222 | }); 223 | expect(result).toBe(false); 224 | }); 225 | 226 | it("should return false if filteredMask has the same length as rawValue", () => { 227 | const result = isValidInput({ 228 | value: "a", 229 | currentMaskChar: "A", 230 | filteredMask: "AAA", 231 | rawValue: "abc", 232 | charRegex, 233 | numRegex, 234 | }); 235 | expect(result).toBe(false); 236 | }); 237 | 238 | it("should return true if value and currentMaskChar are both letters", () => { 239 | const result = isValidInput({ 240 | value: "a", 241 | currentMaskChar: "A", 242 | filteredMask: "AAA", 243 | rawValue: "a", 244 | charRegex, 245 | numRegex, 246 | }); 247 | expect(result).toBe(true); 248 | }); 249 | 250 | it("should return true if value and currentMaskChar are both digits", () => { 251 | const result = isValidInput({ 252 | value: "1", 253 | currentMaskChar: "9", 254 | filteredMask: "999", 255 | rawValue: "1", 256 | charRegex, 257 | numRegex, 258 | }); 259 | expect(result).toBe(true); 260 | }); 261 | 262 | it("should return true if currentMaskChar is a wildcard", () => { 263 | const result = isValidInput({ 264 | value: "a", 265 | currentMaskChar: "*", 266 | filteredMask: "**", 267 | rawValue: "a", 268 | charRegex, 269 | numRegex, 270 | }); 271 | expect(result).toBe(true); 272 | }); 273 | 274 | it("should return false if value is a digit and currentMaskChar is a letter", () => { 275 | const result = isValidInput({ 276 | value: "1", 277 | currentMaskChar: "A", 278 | filteredMask: "AAA", 279 | rawValue: "a", 280 | charRegex, 281 | numRegex, 282 | }); 283 | expect(result).toBe(false); 284 | }); 285 | 286 | it("should return false if value is a letter and currentMaskChar is a digit", () => { 287 | const result = isValidInput({ 288 | value: "a", 289 | currentMaskChar: "9", 290 | filteredMask: "999", 291 | rawValue: "1", 292 | charRegex, 293 | numRegex, 294 | }); 295 | expect(result).toBe(false); 296 | }); 297 | }); 298 | 299 | describe("isWholeInputSelected", () => { 300 | const mask = "(___) ___-____"; 301 | 302 | it("returns true when whole input is selected", () => { 303 | const input = document.createElement("input"); 304 | input.value = "(123) 4567-8911"; 305 | input.selectionStart = 0; 306 | input.selectionEnd = mask.length; 307 | 308 | expect(isWholeInputSelected(input, mask)).toBe(true); 309 | }); 310 | 311 | it("returns false when only part of input is selected", () => { 312 | const input = document.createElement("input"); 313 | input.value = "1234567890"; 314 | input.selectionStart = 0; 315 | input.selectionEnd = 5; 316 | 317 | expect(isWholeInputSelected(input, mask)).toBe(false); 318 | }); 319 | 320 | it("returns false when no input is selected", () => { 321 | const input = document.createElement("input"); 322 | input.value = "1234567890"; 323 | input.selectionStart = input.selectionEnd = 5; 324 | 325 | expect(isWholeInputSelected(input, mask)).toBe(false); 326 | }); 327 | 328 | it("returns false when input is empty", () => { 329 | const input = document.createElement("input"); 330 | input.value = ""; 331 | input.selectionStart = input.selectionEnd = 0; 332 | 333 | expect(isWholeInputSelected(input, mask)).toBe(false); 334 | }); 335 | }); 336 | 337 | describe("getNonMaskedCharCount", () => { 338 | it("returns 0 for empty mask and any raw length", () => { 339 | expect(getNonMaskedCharCount("", 0)).toBe(0); 340 | expect(getNonMaskedCharCount("", 1)).toBe(0); 341 | expect(getNonMaskedCharCount("", 10)).toBe(0); 342 | }); 343 | 344 | it("returns 0 for mask containing non mask characters that haven't been reached", () => { 345 | expect(getNonMaskedCharCount("***-***-****", 0)).toBe(0); 346 | expect(getNonMaskedCharCount("***-***-****", 1)).toBe(0); 347 | expect(getNonMaskedCharCount("***-***-****", 2)).toBe(0); 348 | expect(getNonMaskedCharCount("***-***-****", 3)).toBe(0); 349 | }); 350 | 351 | it("returns proper char count when the placeholders have been reached", () => { 352 | expect(getNonMaskedCharCount("***-***-****", 3)).toBe(0); 353 | expect(getNonMaskedCharCount("***-***-****", 4)).toBe(1); 354 | expect(getNonMaskedCharCount("***-***-****", 10)).toBe(2); 355 | expect(getNonMaskedCharCount("9999 9999 9999 9999", 10)).toBe(2); 356 | expect(getNonMaskedCharCount("9999 9999 9999 9999", 12)).toBe(2); 357 | expect(getNonMaskedCharCount("9999 9999 9999 9999", 13)).toBe(3); 358 | }); 359 | 360 | it("returns 0 when there are no placeholder characters no matter of position reached", () => { 361 | expect(getNonMaskedCharCount("9A***9", 0)).toBe(0); 362 | expect(getNonMaskedCharCount("9A***9", 1)).toBe(0); 363 | expect(getNonMaskedCharCount("9A***9", 10)).toBe(0); 364 | }); 365 | }); 366 | 367 | describe("generateMaskValue", () => { 368 | const charRegex = LETTER_REGEX; 369 | const numRegex = DIGIT_REGEX; 370 | const placeholderChar = "_"; 371 | 372 | it("returns default values when value length is less than mask length", () => { 373 | const result = generateMaskValue( 374 | "A9A-9A9", 375 | "abc", 376 | charRegex, 377 | numRegex, 378 | placeholderChar 379 | ); 380 | expect(result).toEqual({ 381 | maskValue: "___-___", 382 | rawValue: "", 383 | }); 384 | }); 385 | 386 | it("returns default values when value length is greater than mask length", () => { 387 | const result = generateMaskValue( 388 | "A9A-9A9", 389 | "abc12345", 390 | charRegex, 391 | numRegex, 392 | placeholderChar 393 | ); 394 | expect(result).toEqual({ 395 | maskValue: "___-___", 396 | rawValue: "", 397 | }); 398 | }); 399 | 400 | it("returns mask value and raw value when mask and value match", () => { 401 | const result = generateMaskValue( 402 | "AAA-999", 403 | "abc-123", 404 | charRegex, 405 | numRegex, 406 | placeholderChar 407 | ); 408 | expect(result).toEqual({ 409 | maskValue: "abc-123", 410 | rawValue: "abc123", 411 | }); 412 | }); 413 | 414 | it("returns mask value with placeholder when mask and value don't match", () => { 415 | const result = generateMaskValue( 416 | "A9A-9A9", 417 | "a!b@c#d$e", 418 | charRegex, 419 | numRegex, 420 | placeholderChar 421 | ); 422 | expect(result).toEqual({ 423 | maskValue: "___-___", 424 | rawValue: "", 425 | }); 426 | }); 427 | 428 | it("returns mask value with placeholder containing special non mask characters properly", () => { 429 | const result = generateMaskValue( 430 | "AAA-BBBB", 431 | "123abc45", 432 | charRegex, 433 | numRegex, 434 | placeholderChar 435 | ); 436 | expect(result).toEqual({ 437 | maskValue: "___-BBBB", 438 | rawValue: "", 439 | }); 440 | }); 441 | 442 | it("returns mask value with placeholder when value contains non-alphanumeric characters for an alphanumeric mask character", () => { 443 | const result = generateMaskValue( 444 | "A9A-9A9", 445 | "a!b@c#d$e", 446 | charRegex, 447 | numRegex, 448 | placeholderChar 449 | ); 450 | expect(result).toEqual({ 451 | maskValue: "___-___", 452 | rawValue: "", 453 | }); 454 | }); 455 | }); 456 | 457 | describe("generateRawValue", () => { 458 | const charRegex = LETTER_REGEX; 459 | const numRegex = DIGIT_REGEX; 460 | const placeholderChar = "_"; 461 | 462 | test("returns default values if mask or value are empty", () => { 463 | expect( 464 | generateRawValue("", "", charRegex, numRegex, placeholderChar) 465 | ).toEqual({ 466 | maskValue: "", 467 | rawValue: "", 468 | }); 469 | expect( 470 | generateRawValue("A9A-9A9", "", charRegex, numRegex, placeholderChar) 471 | ).toEqual({ 472 | maskValue: "___-___", 473 | rawValue: "", 474 | }); 475 | }); 476 | 477 | test("returns default values if mask contains no mask characters", () => { 478 | expect( 479 | generateRawValue("abc", "abc", charRegex, numRegex, placeholderChar) 480 | ).toEqual({ 481 | maskValue: "abc", 482 | rawValue: "", 483 | }); 484 | }); 485 | 486 | test("returns default values if value length doesn't match mask length", () => { 487 | expect( 488 | generateRawValue("A9A-9A9", "123", charRegex, numRegex, placeholderChar) 489 | ).toEqual({ 490 | maskValue: "___-___", 491 | rawValue: "", 492 | }); 493 | }); 494 | 495 | test("returns default values if input contains invalid characters", () => { 496 | expect( 497 | generateRawValue("A9A-9A9", "abcde", charRegex, numRegex, placeholderChar) 498 | ).toEqual({ 499 | maskValue: "___-___", 500 | rawValue: "", 501 | }); 502 | expect( 503 | generateRawValue( 504 | "A9A-9A9", 505 | "12#-345", 506 | charRegex, 507 | numRegex, 508 | placeholderChar 509 | ) 510 | ).toEqual({ 511 | maskValue: "___-___", 512 | rawValue: "", 513 | }); 514 | }); 515 | 516 | test("returns masked and raw values when input is valid", () => { 517 | expect( 518 | generateRawValue( 519 | "A9A-9A9", 520 | "A1B2C3", 521 | charRegex, 522 | numRegex, 523 | placeholderChar 524 | ) 525 | ).toEqual({ 526 | maskValue: "A1B-2C3", 527 | rawValue: "A1B2C3", 528 | }); 529 | expect( 530 | generateRawValue( 531 | "A9A-9A9", 532 | "a1b2c3", 533 | charRegex, 534 | numRegex, 535 | placeholderChar 536 | ) 537 | ).toEqual({ 538 | maskValue: "a1b-2c3", 539 | rawValue: "a1b2c3", 540 | }); 541 | }); 542 | }); 543 | 544 | describe("isMaskChar", () => { 545 | test("returns true when the character is 'A'", () => { 546 | expect(isMaskChar("A")).toBe(true); 547 | }); 548 | 549 | test("returns true when the character is '9'", () => { 550 | expect(isMaskChar("9")).toBe(true); 551 | }); 552 | 553 | test("returns true when the character is '*'", () => { 554 | expect(isMaskChar("*")).toBe(true); 555 | }); 556 | 557 | test("returns false when the character is not 'A', '9', or '*'", () => { 558 | expect(isMaskChar("a")).toBe(false); 559 | expect(isMaskChar("1")).toBe(false); 560 | expect(isMaskChar("#")).toBe(false); 561 | }); 562 | }); 563 | 564 | describe("generateDefaultValues", () => { 565 | it("should return default values when mask and value are empty", () => { 566 | const result = generateDefaultValues("", "", "raw", /[A-Za-z]/, /\d/, "*"); 567 | expect(result).toEqual({ 568 | maskValue: "", 569 | rawValue: "", 570 | }); 571 | }); 572 | 573 | it("should generate mask value and raw value for raw input", () => { 574 | const result = generateDefaultValues( 575 | "AAA-9999", 576 | "abc1234", 577 | "raw", 578 | /[A-Za-z]/, 579 | /\d/, 580 | "*" 581 | ); 582 | expect(result).toEqual({ 583 | maskValue: "abc-1234", 584 | rawValue: "abc1234", 585 | }); 586 | }); 587 | 588 | it("should generate mask value and raw value for mask input", () => { 589 | const result = generateDefaultValues( 590 | "AAA-9999", 591 | "abc-1234", 592 | "mask", 593 | /[A-Za-z]/, 594 | /\d/, 595 | "*" 596 | ); 597 | expect(result).toEqual({ 598 | maskValue: "abc-1234", 599 | rawValue: "abc1234", 600 | }); 601 | }); 602 | 603 | it("should return partial values when mask and value have different lengths for raw input", () => { 604 | const result = generateDefaultValues( 605 | "AAA-9999", 606 | "abc", 607 | "raw", 608 | /[A-Za-z]/, 609 | /\d/, 610 | "*" 611 | ); 612 | expect(result).toEqual({ 613 | maskValue: "abc-****", 614 | rawValue: "abc", 615 | }); 616 | }); 617 | 618 | it("should return default values when mask and value have different lengths for mask input", () => { 619 | const result = generateDefaultValues( 620 | "AAA-9999", 621 | "abc-12", 622 | "mask", 623 | /[A-Za-z]/, 624 | /\d/, 625 | "*" 626 | ); 627 | expect(result).toEqual({ 628 | maskValue: "***-****", 629 | rawValue: "", 630 | }); 631 | }); 632 | 633 | it("should return default values when input is invalid for raw input", () => { 634 | const result = generateDefaultValues( 635 | "AAA-9999", 636 | "123-abc", 637 | "raw", 638 | /[A-Za-z]/, 639 | /\d/, 640 | "*" 641 | ); 642 | expect(result).toEqual({ 643 | maskValue: "***-****", 644 | rawValue: "", 645 | }); 646 | }); 647 | 648 | it("should return default values when input is invalid for mask input", () => { 649 | const result = generateDefaultValues( 650 | "AAA-9999", 651 | "123abc", 652 | "mask", 653 | /[A-Za-z]/, 654 | /\d/, 655 | "*" 656 | ); 657 | expect(result).toEqual({ 658 | maskValue: "***-****", 659 | rawValue: "", 660 | }); 661 | }); 662 | }); 663 | 664 | describe("triggerInputChange", () => { 665 | it("should trigger a change event on the input element", () => { 666 | const input = document.createElement("input"); 667 | const inputValue = "test"; 668 | vi.spyOn(input, "dispatchEvent"); 669 | triggerInputChange(input, inputValue); 670 | expect(input.value).toBe(inputValue); 671 | expect(input.dispatchEvent).toHaveBeenCalled(); 672 | expect(input.dispatchEvent).toHaveBeenCalledWith( 673 | expect.objectContaining({ 674 | type: "change", 675 | }) 676 | ); 677 | }); 678 | 679 | it("should properly set the value of the input element", () => { 680 | const input = document.createElement("input"); 681 | const inputValue = "test"; 682 | triggerInputChange(input, inputValue); 683 | expect(input.value).toBe(inputValue); 684 | }); 685 | }); 686 | --------------------------------------------------------------------------------