├── src
├── __tests__
│ └── index.test.tsx
├── index.ts
├── mask-resolver.js
├── masks
│ ├── only-letters.mask.js
│ ├── only-numbers.mask.js
│ ├── zip-code.mask.js
│ ├── index.js
│ ├── _base.mask.js
│ ├── datetime.mask.js
│ ├── cnpj.mask.js
│ ├── credit-card.mask.js
│ ├── cel-phone.mask.js
│ ├── cpf.mask.js
│ ├── custom.mask.js
│ └── money.mask.js
├── text-mask.js
├── mask-service.ts
├── base-text-component.ts
├── internal-dependencies
│ └── vanilla-masker.js
├── types.ts
└── text-input-mask.tsx
├── .gitattributes
├── babel.config.js
├── example
├── index.js
├── babel.config.js
├── app.json
├── package.json
├── webpack.config.js
├── src
│ └── App.tsx
└── metro.config.js
├── .editorconfig
├── .gitignore
├── tsconfig.json
├── LICENSE
├── .circleci
└── config.yml
├── package.json
├── CONTRIBUTING.md
└── README.md
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | it.todo('write a test');
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import Input from './text-input-mask';
2 |
3 | export { default as MaskService } from './mask-service';
4 | export { default as TextInputMask } from './text-input-mask';
5 |
6 | export default Input;
7 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { registerRootComponent } from 'expo';
2 |
3 | import App from './src/App';
4 |
5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App);
6 | // It also ensures that whether you load the app in the Expo client or in a native build,
7 | // the environment is set up appropriately
8 | registerRootComponent(App);
9 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/src/mask-resolver.js:
--------------------------------------------------------------------------------
1 | import * as Masks from './masks';
2 |
3 | var maskKeys = Object.keys(Masks);
4 |
5 | export default class MaskResolver {
6 | static resolve(type) {
7 | let maskKey = maskKeys.find((m) => {
8 | var handler = Masks[m];
9 | return handler && handler.getType && handler.getType() === type;
10 | });
11 |
12 | let handler = Masks[maskKey];
13 |
14 | if (!handler) {
15 | throw new Error('Mask type not supported.');
16 | }
17 |
18 | return new handler();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = function (api) {
5 | api.cache(true);
6 |
7 | return {
8 | presets: ['babel-preset-expo'],
9 | plugins: [
10 | [
11 | 'module-resolver',
12 | {
13 | alias: {
14 | // For development, we want to alias the library to the source
15 | [pak.name]: path.join(__dirname, '..', pak.source),
16 | },
17 | },
18 | ],
19 | ],
20 | };
21 | };
22 |
--------------------------------------------------------------------------------
/src/masks/only-letters.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 |
3 | export default class OnlyLettersMask extends BaseMask {
4 | static getType() {
5 | return 'only-letters';
6 | }
7 |
8 | getValue(value, settings) {
9 | return this.removeNotLetters(String(value));
10 | }
11 |
12 | getRawValue(maskedValue, settings) {
13 | return super.removeNotLetters(String(maskedValue));
14 | }
15 |
16 | validate(value, settings) {
17 | return true;
18 | }
19 |
20 | getMask(value, settings) {
21 | return '';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/masks/only-numbers.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 |
3 | export default class OnlyNumbersMask extends BaseMask {
4 | static getType() {
5 | return 'only-numbers';
6 | }
7 |
8 | getValue(value, settings) {
9 | return this.removeNotNumbers(String(value));
10 | }
11 |
12 | getRawValue(maskedValue, settings) {
13 | return super.removeNotNumbers(String(maskedValue));
14 | }
15 |
16 | validate(value, settings) {
17 | return true;
18 | }
19 |
20 | getMask(value, settings) {
21 | return '';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/text-mask.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Text } from 'react-native';
3 | import BaseTextComponent from './base-text-component';
4 |
5 | const TEXT_REF = '$text';
6 |
7 | export default class TextMask extends BaseTextComponent {
8 | constructor(props) {
9 | super(props);
10 | }
11 |
12 | getElement() {
13 | return this.refs[TEXT_REF];
14 | }
15 |
16 | render() {
17 | return (
18 |
19 | {this.getDisplayValueFor(this.props.value)}
20 |
21 | );
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-masked-input-example",
3 | "displayName": "MaskedInput Example",
4 | "expo": {
5 | "name": "react-native-masked-input-example",
6 | "slug": "react-native-masked-input-example",
7 | "description": "Example app for react-native-masked-input",
8 | "privacy": "public",
9 | "version": "1.0.0",
10 | "platforms": [
11 | "ios",
12 | "android",
13 | "web"
14 | ],
15 | "ios": {
16 | "supportsTablet": true
17 | },
18 | "assetBundlePatterns": [
19 | "**/*"
20 | ]
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/masks/zip-code.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import CustomMask from './custom.mask';
3 |
4 | const ZIP_CODE_MASK = '99999-999';
5 |
6 | const MASK_OPTIONS = {
7 | mask: ZIP_CODE_MASK,
8 | };
9 |
10 | export default class ZipCodeMask extends BaseMask {
11 | static getType() {
12 | return 'zip-code';
13 | }
14 |
15 | getValue(value, settings) {
16 | return CustomMask.shared.getValue(value, MASK_OPTIONS);
17 | }
18 |
19 | getRawValue(maskedValue, settings) {
20 | return super.removeNotNumbers(maskedValue);
21 | }
22 |
23 | validate(value, settings) {
24 | if (value) {
25 | return value.length === ZIP_CODE_MASK.length;
26 | }
27 |
28 | return value.length > 0;
29 | }
30 |
31 | getMask(value, settings) {
32 | return ZIP_CODE_MASK;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .idea
35 | .gradle
36 | local.properties
37 | android.iml
38 |
39 | # Cocoapods
40 | #
41 | example/ios/Pods
42 |
43 | # node.js
44 | #
45 | node_modules/
46 | npm-debug.log
47 | yarn-debug.log
48 | yarn-error.log
49 |
50 | # BUCK
51 | buck-out/
52 | \.buckd/
53 | android/app/libs
54 | android/keystores/debug.keystore
55 |
56 | # Expo
57 | .expo/*
58 | lib/
59 | .env
60 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "paths": {
5 | "react-native-masked-input": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "importsNotUsedAsValues": "error",
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext"],
14 | "module": "esnext",
15 | "moduleResolution": "node",
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "allowJs": true,
26 | "target": "esnext"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-masked-input-example",
3 | "description": "Example app for react-native-masked-input",
4 | "version": "0.0.1",
5 | "private": true,
6 | "main": "index",
7 | "scripts": {
8 | "android": "expo start --android",
9 | "ios": "expo start --ios",
10 | "web": "expo start --web",
11 | "start": "expo start",
12 | "test": "jest"
13 | },
14 | "dependencies": {
15 | "expo": "^38.0.0",
16 | "expo-splash-screen": "^0.3.1",
17 | "react": "16.11.0",
18 | "react-dom": "16.11.0",
19 | "react-native": "0.62.2",
20 | "react-native-unimodules": "~0.10.1",
21 | "react-native-web": "^0.12.3"
22 | },
23 | "devDependencies": {
24 | "@babel/core": "^7.9.6",
25 | "@babel/runtime": "^7.9.6",
26 | "babel-plugin-module-resolver": "^4.0.0",
27 | "babel-preset-expo": "^8.2.3",
28 | "expo-cli": "^3.21.12"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/example/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const createExpoWebpackConfigAsync = require('@expo/webpack-config');
3 | const { resolver } = require('./metro.config');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const node_modules = path.join(__dirname, 'node_modules');
7 |
8 | module.exports = async function (env, argv) {
9 | const config = await createExpoWebpackConfigAsync(env, argv);
10 |
11 | config.module.rules.push({
12 | test: /\.(js|ts|tsx)$/,
13 | include: path.resolve(root, 'src'),
14 | use: 'babel-loader',
15 | });
16 |
17 | // We need to make sure that only one version is loaded for peerDependencies
18 | // So we alias them to the versions in example's node_modules
19 | Object.assign(config.resolve.alias, {
20 | ...resolver.extraNodeModules,
21 | 'react-native-web': path.join(node_modules, 'react-native-web'),
22 | });
23 |
24 | return config;
25 | };
26 |
--------------------------------------------------------------------------------
/src/masks/index.js:
--------------------------------------------------------------------------------
1 | import CelPhoneMask from './cel-phone.mask';
2 | import CnpjMask from './cnpj.mask';
3 | import CpfMask from './cpf.mask';
4 | import CustomMask from './custom.mask';
5 | import DatetimeMask from './datetime.mask';
6 | import MoneyMask from './money.mask';
7 | import OnlyNumbersMask from './only-numbers.mask';
8 | import ZipCodeMask from './zip-code.mask';
9 | import CreditCardMask from './credit-card.mask';
10 | import OnlyLettersMask from './only-letters.mask';
11 |
12 | module.exports.CelPhoneMask = CelPhoneMask;
13 | module.exports.CnpjMask = CnpjMask;
14 | module.exports.CpfMask = CpfMask;
15 | module.exports.CustomMask = CustomMask;
16 | module.exports.DatetimeMask = DatetimeMask;
17 | module.exports.MoneyMask = MoneyMask;
18 | module.exports.OnlyNumbersMask = OnlyNumbersMask;
19 | module.exports.ZipCodeMask = ZipCodeMask;
20 | module.exports.CreditCardMask = CreditCardMask;
21 | module.exports.OnlyLettersMask = OnlyLettersMask;
22 |
--------------------------------------------------------------------------------
/src/masks/_base.mask.js:
--------------------------------------------------------------------------------
1 | export default class BaseMask {
2 | getKeyboardType() {
3 | return 'numeric';
4 | }
5 |
6 | mergeSettings(obj1, obj2) {
7 | return { ...obj1, ...obj2 };
8 | }
9 |
10 | getRawValue(maskedValue, settings) {
11 | return maskedValue;
12 | }
13 |
14 | getDefaultValue(value) {
15 | if (value === undefined || value === null) {
16 | return '';
17 | }
18 |
19 | return value;
20 | }
21 |
22 | getMask(value, settings) {
23 | throw new Error('getCurrentMask is not implemented');
24 | }
25 |
26 | removeNotNumbersForMoney(text) {
27 | return typeof text === 'number' ? text : text.replace(/[^.,0-9]+/g, '');
28 | }
29 |
30 | removeNotNumbers(text) {
31 | return text.replace(/[^0-9]+/g, '');
32 | }
33 |
34 | removeWhiteSpaces(text) {
35 | return (text || '').replace(/\s/g, '');
36 | }
37 | removeNotLeters(text) {
38 | return text.replace(/\d/g, '');
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { StyleSheet, View } from 'react-native';
3 | import MaskedInput from '../../src/';
4 | import { useCallback } from 'react';
5 |
6 | let options = {
7 | precision: 2,
8 | separator: ',',
9 | delimiter: '.',
10 | unit: '$',
11 | suffixUnit: '$',
12 | zeroCents: true,
13 | };
14 |
15 | export default function App() {
16 | const [result, setResult] = React.useState(0);
17 |
18 | const onChangeCallback = useCallback((maskedText) => {
19 | setResult(maskedText);
20 | }, []);
21 | return (
22 |
23 |
30 |
31 | );
32 | }
33 |
34 | const styles = StyleSheet.create({
35 | container: {
36 | flex: 1,
37 | alignItems: 'center',
38 | justifyContent: 'center',
39 | },
40 | });
41 |
--------------------------------------------------------------------------------
/src/mask-service.ts:
--------------------------------------------------------------------------------
1 | import MaskResolver from './mask-resolver';
2 | import type { TextInputMaskOptionProp, TextInputMaskTypeProp } from './types';
3 |
4 | export default class MaskService {
5 | static toMask(
6 | type: TextInputMaskTypeProp,
7 | value: string,
8 | options?: TextInputMaskOptionProp
9 | ) {
10 | return MaskResolver.resolve(type).getValue(value, options);
11 | }
12 |
13 | static toRawValue(
14 | type: TextInputMaskTypeProp,
15 | maskedValue: string,
16 | options?: TextInputMaskOptionProp
17 | ) {
18 | return MaskResolver.resolve(type).getRawValue(maskedValue, options);
19 | }
20 |
21 | static isValid(
22 | type: TextInputMaskTypeProp,
23 | value: string,
24 | options?: TextInputMaskOptionProp
25 | ) {
26 | return MaskResolver.resolve(type).validate(value, options);
27 | }
28 |
29 | static getMask(
30 | type: TextInputMaskTypeProp,
31 | value: string,
32 | options?: TextInputMaskOptionProp
33 | ) {
34 | return MaskResolver.resolve(type).getMask(value, options);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 thevsstech
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 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const blacklist = require('metro-config/src/defaults/blacklist');
3 | const escape = require('escape-string-regexp');
4 | const pak = require('../package.json');
5 |
6 | const root = path.resolve(__dirname, '..');
7 |
8 | const modules = Object.keys({
9 | ...pak.peerDependencies,
10 | });
11 |
12 | module.exports = {
13 | projectRoot: __dirname,
14 | watchFolders: [root],
15 |
16 | // We need to make sure that only one version is loaded for peerDependencies
17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules
18 | resolver: {
19 | blacklistRE: blacklist(
20 | modules.map(
21 | (m) =>
22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
23 | )
24 | ),
25 |
26 | extraNodeModules: modules.reduce((acc, name) => {
27 | acc[name] = path.join(__dirname, 'node_modules', name);
28 | return acc;
29 | }, {}),
30 | },
31 |
32 | transformer: {
33 | getTransformOptions: async () => ({
34 | transform: {
35 | experimentalImportSupport: false,
36 | inlineRequires: true,
37 | },
38 | }),
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/src/masks/datetime.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import CustomMask from './custom.mask';
3 | import date from 'date-and-time';
4 |
5 | const DATETIME_MASK_SETTINGS = {
6 | format: 'DD/MM/YYYY HH:mm:ss',
7 | };
8 |
9 | export default class DatetimeMask extends BaseMask {
10 | static getType() {
11 | return 'datetime';
12 | }
13 |
14 | getValue(value, settings) {
15 | let mergedSettings = this._getMergedSettings(settings);
16 | let mask = this.getMask(value, mergedSettings);
17 |
18 | return CustomMask.shared.getValue(value, { mask });
19 | }
20 |
21 | getRawValue(maskedValue, settings) {
22 | let mergedSettings = this._getMergedSettings(settings);
23 | return date.parse(maskedValue, mergedSettings.format);
24 | }
25 |
26 | validate(value, settings) {
27 | let maskedValue = this.getValue(value, settings);
28 | let mergedSettings = this._getMergedSettings(settings);
29 | let isValid = date.isValid(maskedValue, mergedSettings.format);
30 | return isValid;
31 | }
32 |
33 | _getMergedSettings(settings) {
34 | return super.mergeSettings(DATETIME_MASK_SETTINGS, settings);
35 | }
36 |
37 | getMask(value, settings) {
38 | let mask = '';
39 |
40 | for (let i = 0; i < settings.format.length; i++) {
41 | mask += settings.format[i].replace(/[a-zA-Z]+/g, '9');
42 | }
43 |
44 | return mask;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/masks/cnpj.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import CustomMask from './custom.mask';
3 |
4 | export const CNPJ_MASK = '99.999.999/9999-99';
5 |
6 | export const validateCnpj = (cnpj) => {
7 | var valida = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
8 | var dig1 = 0;
9 | var dig2 = 0;
10 | var i;
11 |
12 | var exp = /\.\//g;
13 | cnpj = cnpj.toString().replace(exp, '');
14 | var digito = parseInt(cnpj.charAt(12) + cnpj.charAt(13), 10);
15 |
16 | for (i = 0; i < valida.length; i++) {
17 | dig1 += i > 0 ? cnpj.charAt(i - 1) * valida[i] : 0;
18 | dig2 += cnpj.charAt(i) * valida[i];
19 | }
20 | dig1 = dig1 % 11 < 2 ? 0 : 11 - (dig1 % 11);
21 | dig2 = dig2 % 11 < 2 ? 0 : 11 - (dig2 % 11);
22 |
23 | return dig1 * 10 + dig2 === digito;
24 | };
25 |
26 | const customMaskOptions = { mask: CNPJ_MASK };
27 |
28 | export default class CnpjMask extends BaseMask {
29 | static getType() {
30 | return 'cnpj';
31 | }
32 |
33 | getValue(value, settings) {
34 | return CustomMask.shared.getValue(value, customMaskOptions);
35 | }
36 |
37 | getRawValue(maskedValue, settings) {
38 | return super.removeNotNumbers(maskedValue);
39 | }
40 |
41 | validate(value, settings) {
42 | var isEmpty = (value || '').trim().length === 0;
43 | return !isEmpty && validateCnpj(value);
44 | }
45 |
46 | getMask(value, settings) {
47 | return CNPJ_MASK;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/masks/credit-card.mask.js:
--------------------------------------------------------------------------------
1 | import cardTypes from 'credit-card-type';
2 | import BaseMask from './_base.mask';
3 | import CustomMask from './custom.mask';
4 |
5 | const defaultType = { type: 'default', gaps: [4, 8, 12], lengths: [16] };
6 |
7 | const MASK_TRANSLATION = {
8 | '*': (val) => '*',
9 | };
10 |
11 | export default class CreditCardMask extends BaseMask {
12 | static getType() {
13 | return 'credit-card';
14 | }
15 |
16 | getValue(value, settings) {
17 | return CustomMask.shared.getValue(value, {
18 | mask: this.getMask(value, settings),
19 | translation: MASK_TRANSLATION,
20 | });
21 | }
22 |
23 | validate(value) {
24 | if (value) {
25 | const type = this.getCardType(value);
26 | return type.lengths.includes(value.length);
27 | }
28 |
29 | return true;
30 | }
31 |
32 | getRawValue(maskedValue, settings) {
33 | if (!maskedValue) return [];
34 |
35 | return maskedValue.split(' ').map((val) => {
36 | if (!val) return '';
37 |
38 | return val.trim();
39 | });
40 | }
41 |
42 | getMask(value, settings = {}) {
43 | const type = this.getCardType(value);
44 | const length = Math.max(...type.lengths);
45 | const gaps = type.gaps.map((g, i) => g + i);
46 |
47 | const firstGap = gaps[0];
48 | const lastGap = gaps[gaps.length - 1];
49 | return Array.from(new Array(length + gaps.length))
50 | .map((_, i) => {
51 | if (gaps.includes(i)) return ' ';
52 | if (settings.obfuscated && i > firstGap && i < lastGap) return '*';
53 | return 9;
54 | })
55 | .join('');
56 | }
57 |
58 | getCardType(value) {
59 | return cardTypes(value)[0] || defaultType;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/masks/cel-phone.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import CustomMask from './custom.mask';
3 |
4 | const PHONE_8_MASK = '9999-9999';
5 | const PHONE_9_MASK = '99999-9999';
6 | const PHONE_INTERNATIONAL = '+999 999 999 999';
7 |
8 | const MASK_TYPES = {
9 | BRL: 'BRL',
10 | INTERNATIONAL: 'INTERNATIONAL',
11 | };
12 |
13 | const CEL_PHONE_SETTINGS = {
14 | maskType: MASK_TYPES.BRL,
15 | withDDD: true,
16 | dddMask: '(99) ',
17 | };
18 |
19 | export default class CelPhoneMask extends BaseMask {
20 | static getType() {
21 | return 'cel-phone';
22 | }
23 |
24 | getValue(value, settings) {
25 | let cleanedValue = super.removeNotNumbers(value);
26 | let mask = this.getMask(cleanedValue, settings);
27 | return CustomMask.shared.getValue(cleanedValue, { mask });
28 | }
29 |
30 | getRawValue(maskedValue, settings) {
31 | return super.removeNotNumbers(maskedValue);
32 | }
33 |
34 | validate(value, settings) {
35 | let valueToValidate = super.getDefaultValue(value);
36 | valueToValidate = this.getValue(value, settings);
37 |
38 | let mask = this.getMask(value, settings);
39 |
40 | return valueToValidate.length === mask.length;
41 | }
42 |
43 | getMask(value, settings) {
44 | let mergedSettings = super.mergeSettings(CEL_PHONE_SETTINGS, settings);
45 |
46 | if (mergedSettings.maskType === MASK_TYPES.INTERNATIONAL) {
47 | return PHONE_INTERNATIONAL;
48 | }
49 |
50 | let numbers = super.removeNotNumbers(value);
51 | let mask = PHONE_8_MASK;
52 |
53 | let use9DigitMask = (() => {
54 | if (mergedSettings.withDDD) {
55 | let numbersDDD = super.removeNotNumbers(mergedSettings.dddMask);
56 | let remainingValueNumbers = numbers.substr(numbersDDD.length);
57 | return remainingValueNumbers.length >= 9;
58 | } else {
59 | return numbers.length >= 9;
60 | }
61 | })();
62 |
63 | if (use9DigitMask) {
64 | mask = PHONE_9_MASK;
65 | }
66 |
67 | if (mergedSettings.withDDD) {
68 | mask = `${mergedSettings.dddMask}${mask}`;
69 | }
70 |
71 | return mask;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/masks/cpf.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import CustomMask from './custom.mask';
3 |
4 | export const CPF_MASK = '999.999.999-99';
5 |
6 | export const validateCPF = (cpf) => {
7 | if (cpf === '') {
8 | return true;
9 | }
10 |
11 | cpf = cpf.replace(/\./gi, '').replace(/-/gi, '');
12 | var isValid = true;
13 | var sum;
14 | var rest;
15 | var i;
16 | i = 0;
17 | sum = 0;
18 |
19 | if (
20 | cpf.length !== 11 ||
21 | cpf === '00000000000' ||
22 | cpf === '11111111111' ||
23 | cpf === '22222222222' ||
24 | cpf === '33333333333' ||
25 | cpf === '44444444444' ||
26 | cpf === '55555555555' ||
27 | cpf === '66666666666' ||
28 | cpf === '77777777777' ||
29 | cpf === '88888888888' ||
30 | cpf === '99999999999'
31 | ) {
32 | isValid = false;
33 | }
34 |
35 | for (i = 1; i <= 9; i++) {
36 | sum = sum + parseInt(cpf.substring(i - 1, i), 10) * (11 - i);
37 | }
38 |
39 | rest = (sum * 10) % 11;
40 |
41 | if (rest === 10 || rest === 11) {
42 | rest = 0;
43 | }
44 |
45 | if (rest !== parseInt(cpf.substring(9, 10), 10)) {
46 | isValid = false;
47 | }
48 |
49 | sum = 0;
50 |
51 | for (i = 1; i <= 10; i++) {
52 | sum = sum + parseInt(cpf.substring(i - 1, i), 10) * (12 - i);
53 | }
54 |
55 | rest = (sum * 10) % 11;
56 |
57 | if (rest === 10 || rest === 11) {
58 | rest = 0;
59 | }
60 | if (rest !== parseInt(cpf.substring(10, 11), 10)) {
61 | isValid = false;
62 | }
63 |
64 | return isValid;
65 | };
66 |
67 | const maskOptions = { mask: CPF_MASK };
68 |
69 | export default class CpfMask extends BaseMask {
70 | static getType() {
71 | return 'cpf';
72 | }
73 |
74 | getValue(value, settings) {
75 | return CustomMask.shared.getValue(value, maskOptions);
76 | }
77 |
78 | getRawValue(maskedValue, settings) {
79 | return super.removeNotNumbers(maskedValue);
80 | }
81 |
82 | validate(value, settings) {
83 | var isEmpty = (value || '').trim().length === 0;
84 | return !isEmpty && validateCPF(value);
85 | }
86 |
87 | getMask(value, settings) {
88 | return CPF_MASK;
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/base-text-component.ts:
--------------------------------------------------------------------------------
1 | import { PureComponent } from 'react';
2 | import MaskResolver from './mask-resolver';
3 | import type {
4 | MaskHandlerInterface,
5 | MaskHandlerReturnType,
6 | TextInputMaskProps,
7 | ValueType,
8 | } from './types';
9 |
10 | export default class BaseTextComponent<
11 | T extends TextInputMaskProps,
12 | S extends any
13 | > extends PureComponent {
14 | _maskHandler!: MaskHandlerInterface;
15 | constructor(props: T) {
16 | super(props);
17 | this._resolveMaskHandler();
18 | }
19 |
20 | componentDidMount() {
21 | this._bindProps(this.props);
22 | }
23 |
24 | componentDidUpdate(prevProps: T) {
25 | this._bindProps(prevProps);
26 | }
27 |
28 | updateValue(text: ValueType): MaskHandlerReturnType {
29 | let maskedText = this._getMaskedValue(text);
30 | const rawText = this.getRawValueFor(maskedText);
31 |
32 | return {
33 | maskedText,
34 | rawText,
35 | };
36 | }
37 |
38 | isValid() {
39 | return this._maskHandler.validate(
40 | this._getDefaultValue(this.props.value as any),
41 | this._getOptions()
42 | );
43 | }
44 |
45 | getRawValueFor(value: ValueType) {
46 | return this._maskHandler.getRawValue(
47 | this._getDefaultValue(value),
48 | this._getOptions()
49 | );
50 | }
51 |
52 | getRawValue() {
53 | return this.getRawValueFor(this.props.value as any);
54 | }
55 |
56 | _getOptions() {
57 | return this.props.options;
58 | }
59 |
60 | _mustUpdateValue(newValue: ValueType) {
61 | return this.props.value !== newValue;
62 | }
63 |
64 | _resolveMaskHandler() {
65 | this._maskHandler = MaskResolver.resolve(this.props.type);
66 | }
67 |
68 | _bindProps(nextProps: T) {
69 | if (this.props.type !== nextProps.type) {
70 | this._resolveMaskHandler();
71 | }
72 | }
73 |
74 | _getDefaultMaskedValue(value: ValueType) {
75 | if (this._getDefaultValue(value) === '') {
76 | return '';
77 | }
78 |
79 | return this._getMaskedValue(value);
80 | }
81 |
82 | _getMaskedValue(value: ValueType) {
83 | const defaultValue = this._getDefaultValue(value);
84 | if (defaultValue === '') {
85 | return '';
86 | }
87 |
88 | return this._maskHandler.getValue(defaultValue, this._getOptions());
89 | }
90 |
91 | _getDefaultValue(value: ValueType) {
92 | if (value === undefined || value === null) {
93 | return '';
94 | }
95 |
96 | return value;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | executors:
4 | default:
5 | docker:
6 | - image: circleci/node:10
7 | working_directory: ~/project
8 |
9 | commands:
10 | attach_project:
11 | steps:
12 | - attach_workspace:
13 | at: ~/project
14 |
15 | jobs:
16 | install-dependencies:
17 | executor: default
18 | steps:
19 | - checkout
20 | - attach_project
21 | - restore_cache:
22 | keys:
23 | - dependencies-{{ checksum "package.json" }}
24 | - dependencies-
25 | - restore_cache:
26 | keys:
27 | - dependencies-example-{{ checksum "example/package.json" }}
28 | - dependencies-example-
29 | - run:
30 | name: Install dependencies
31 | command: |
32 | yarn install --cwd example --frozen-lockfile
33 | yarn install --frozen-lockfile
34 | - save_cache:
35 | key: dependencies-{{ checksum "package.json" }}
36 | paths: node_modules
37 | - save_cache:
38 | key: dependencies-example-{{ checksum "example/package.json" }}
39 | paths: example/node_modules
40 | - persist_to_workspace:
41 | root: .
42 | paths: .
43 |
44 | lint:
45 | executor: default
46 | steps:
47 | - attach_project
48 | - run:
49 | name: Lint files
50 | command: |
51 | yarn lint
52 |
53 | typescript:
54 | executor: default
55 | steps:
56 | - attach_project
57 | - run:
58 | name: Typecheck files
59 | command: |
60 | yarn typescript
61 |
62 | unit-tests:
63 | executor: default
64 | steps:
65 | - attach_project
66 | - run:
67 | name: Run unit tests
68 | command: |
69 | yarn test --coverage
70 | - store_artifacts:
71 | path: coverage
72 | destination: coverage
73 |
74 | build-package:
75 | executor: default
76 | steps:
77 | - attach_project
78 | - run:
79 | name: Build package
80 | command: |
81 | yarn prepare
82 |
83 | workflows:
84 | build-and-test:
85 | jobs:
86 | - install-dependencies
87 | - lint:
88 | requires:
89 | - install-dependencies
90 | - typescript:
91 | requires:
92 | - install-dependencies
93 | - unit-tests:
94 | requires:
95 | - install-dependencies
96 | - build-package:
97 | requires:
98 | - install-dependencies
99 |
--------------------------------------------------------------------------------
/src/masks/custom.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 |
3 | function getDefaultTranslation() {
4 | return {
5 | '9': function (val) {
6 | return val.replace(/[^0-9]+/g, '');
7 | },
8 | 'A': function (val) {
9 | return val.replace(/[^a-zA-Z]+/g, '');
10 | },
11 | 'S': function (val) {
12 | return val.replace(/[^a-zA-Z0-9]+/g, '');
13 | },
14 | '*': function (val) {
15 | return val;
16 | },
17 | };
18 | }
19 |
20 | function toPattern(value, mask, translation) {
21 | let result = '';
22 |
23 | let maskCharIndex = 0;
24 | let valueCharIndex = 0;
25 |
26 | while (true) {
27 | // if mask is ended, break.
28 | if (maskCharIndex === mask.length) {
29 | break;
30 | }
31 |
32 | // if value is ended, break.
33 | if (valueCharIndex === value.length) {
34 | break;
35 | }
36 |
37 | let maskChar = mask[maskCharIndex];
38 | let valueChar = value[valueCharIndex];
39 |
40 | // value equals mask, just set
41 | if (maskChar === valueChar) {
42 | result += maskChar;
43 | valueCharIndex += 1;
44 | maskCharIndex += 1;
45 | continue;
46 | }
47 |
48 | // apply translator if match
49 | const translationHandler = translation[maskChar];
50 |
51 | if (translationHandler) {
52 | const resolverValue = translationHandler(valueChar || '');
53 | if (resolverValue === '') {
54 | //valueChar replaced so don't add it to result, keep the mask at the same point and continue to next value char
55 | valueCharIndex += 1;
56 | continue;
57 | } else if (resolverValue !== null) {
58 | result += resolverValue;
59 | valueCharIndex += 1;
60 | } else {
61 | result += maskChar;
62 | }
63 | maskCharIndex += 1;
64 | continue;
65 | }
66 |
67 | // not masked value, fixed char on mask
68 | result += maskChar;
69 | maskCharIndex += 1;
70 | continue;
71 | }
72 |
73 | return result;
74 | }
75 |
76 | const DEFAULT_TRANSLATION = getDefaultTranslation();
77 |
78 | export default class CustomMask extends BaseMask {
79 | static getType() {
80 | return 'custom';
81 | }
82 |
83 | static getDefaultTranslation() {
84 | return getDefaultTranslation();
85 | }
86 |
87 | static shared = new CustomMask();
88 |
89 | getKeyboardType() {
90 | return 'default';
91 | }
92 |
93 | getValue(value, settings) {
94 | if (value === '') {
95 | return value;
96 | }
97 | let { mask } = settings;
98 | let translation = this.mergeSettings(
99 | DEFAULT_TRANSLATION,
100 | settings.translation
101 | );
102 |
103 | var masked = toPattern(value, mask, translation);
104 | return masked;
105 | }
106 |
107 | getRawValue(maskedValue, settings) {
108 | if (!!settings && settings.getRawValue) {
109 | return settings.getRawValue(maskedValue, settings);
110 | }
111 |
112 | return maskedValue;
113 | }
114 |
115 | validate(value, settings) {
116 | if (!!settings && settings.validator) {
117 | return settings.validator(value, settings);
118 | }
119 |
120 | return true;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/src/internal-dependencies/vanilla-masker.js:
--------------------------------------------------------------------------------
1 | const mergeMoneyOptions = function (opts) {
2 | opts = opts || {};
3 | opts = {
4 | precision: opts.hasOwnProperty('precision') ? opts.precision : 2,
5 | separator: opts.separator || ',',
6 | delimiter: opts.delimiter || '.',
7 | unit: opts.unit ? opts.unit : '',
8 | //unit: opts.unit && (opts.unit.replace(/[\s]/g,'') + " ") || "",
9 | suffixUnit:
10 | (opts.suffixUnit && ' ' + opts.suffixUnit.replace(/[\s]/g, '')) || '',
11 | zeroCents: opts.zeroCents,
12 | lastOutput: opts.lastOutput,
13 | };
14 | opts.moneyPrecision = opts.zeroCents ? 0 : opts.precision;
15 | return opts;
16 | };
17 |
18 | const addSeparators = (value, separator = ',') => {
19 | return value.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
20 | };
21 |
22 | class VMasker {
23 | toMoney(value, opts) {
24 | opts = mergeMoneyOptions(opts);
25 |
26 | if (value === '-') {
27 | return '-';
28 | }
29 | value = value.toString();
30 | const isNegative = value.includes('-');
31 | const decimalSeparator = opts.delimiter;
32 | const [int, decimals] = value.split('.');
33 |
34 | const valueOnlyInt = isNegative ? int.replace('-', '') : int;
35 |
36 | const includePrefix = opts.unit ? opts.unit : '';
37 | const includeNegative = isNegative ? '-' : '';
38 | const formattedInt = addSeparators(valueOnlyInt, opts.separator);
39 | const fillWithZeroCount = opts.zeroCents
40 | ? opts.precision - (decimals ? decimals.length : 0)
41 | : 0;
42 |
43 | const includedZeroCents =
44 | fillWithZeroCount && fillWithZeroCount > 0
45 | ? Array(fillWithZeroCount).fill(0).join('')
46 | : '';
47 | const includeDecimals = (value.includes('.')
48 | ? `${decimalSeparator}${decimals}${includedZeroCents}`
49 | : fillWithZeroCount
50 | ? decimalSeparator + includedZeroCents
51 | : ''
52 | ).slice(0, opts.precision + 1);
53 |
54 | let data = `${includeNegative}${includePrefix}${formattedInt}${includeDecimals}`;
55 |
56 | return data;
57 | }
58 | }
59 |
60 | /*VMasker.toPattern = function (value, opts) {
61 | var pattern = typeof opts === 'object' ? opts.pattern : opts,
62 | patternChars = pattern.replace(/\W/g, ''),
63 | output = pattern.split(''),
64 | values = value.toString().replace(/\W/g, ''),
65 | charsValues = values.replace(/\W/g, ''),
66 | index = 0,
67 | i,
68 | outputLength = output.length,
69 | placeholder = typeof opts === 'object' ? opts.placeholder : undefined;
70 | for (i = 0; i < outputLength; i++) {
71 | // Reached the end of input
72 | if (index >= values.length) {
73 | if (patternChars.length === charsValues.length) {
74 | return output.join('');
75 | } else if (
76 | placeholder !== undefined &&
77 | patternChars.length > charsValues.length
78 | ) {
79 | return addPlaceholdersToOutput(output, i, placeholder).join('');
80 | } else {
81 | break;
82 | }
83 | }
84 | // Remaining chars in input
85 | else {
86 | if (
87 | (output[i] === DIGIT && values[index].match(/[0-9]/)) ||
88 | (output[i] === ALPHA && values[index].match(/[a-zA-Z]/)) ||
89 | (output[i] === ALPHANUM && values[index].match(/[0-9a-zA-Z]/))
90 | ) {
91 | output[i] = values[index++];
92 | } else if (
93 | output[i] === DIGIT ||
94 | output[i] === ALPHA ||
95 | output[i] === ALPHANUM
96 | ) {
97 | if (placeholder !== undefined) {
98 | return addPlaceholdersToOutput(output, i, placeholder).join('');
99 | } else {
100 | return output.slice(0, i).join('');
101 | }
102 | }
103 | }
104 | }
105 | return output.join('').substr(0, i);
106 | };*/
107 |
108 | const VMaskerObject = new VMasker();
109 |
110 | export default VMaskerObject;
111 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Type Definition.
3 | *
4 | * Using with Typescript development.
5 | *
6 | * Definitions by: Italo Izaac
7 | */
8 |
9 | import type { TextInput, TextInputProps } from 'react-native';
10 | import type { ReactText, Ref } from 'react';
11 |
12 | // Type prop of TextInputMask.
13 | export type TextInputMaskTypeProp =
14 | | 'credit-card'
15 | | 'cpf'
16 | | 'cnpj'
17 | | 'zip-code'
18 | | 'only-numbers'
19 | | 'money'
20 | | 'cel-phone'
21 | | 'datetime'
22 | | 'custom'
23 | | 'only-letters';
24 |
25 | export type MaskHandlerReturnType = { maskedText: string; rawText: number };
26 |
27 | export type ValueType = ReactText;
28 |
29 | export interface MaskHandlerInterface<
30 | Options extends TextInputOptionBaseInterface
31 | > {
32 | getMask: (value: ValueType, settings?: Options) => string;
33 | getRawValue: (maskedValue: ValueType, settings: Options) => number;
34 | validate: (value: ValueType, settings?: Options) => void;
35 | getValue: (value: ValueType, settings?: Options) => string;
36 | handleBlur?: (value: ValueType, settings?: Options) => MaskHandlerReturnType;
37 | handleFocus?: (value: ValueType, settings?: Options) => MaskHandlerReturnType;
38 | handleInit?: (value: ValueType, settings: Options) => MaskHandlerReturnType;
39 | handleChange?: (value: ValueType, settings: Options) => MaskHandlerReturnType;
40 | getKeyboardType?: () => string;
41 | }
42 |
43 | export interface TextInputMoneyMaskOptions {
44 | // Money type.
45 | precision?: number;
46 | separator?: string;
47 | delimiter?: string;
48 | unit?: string;
49 | suffixUnit?: string;
50 | zeroCents?: boolean;
51 | }
52 |
53 | export interface TextInputPhoneOptions {
54 | withDDD?: boolean;
55 | dddMask?: string;
56 | maskType?: 'BRL' | 'INTERNATIONAL';
57 | }
58 |
59 | export type SupportedCreditCardIssuers =
60 | | 'visa-or-mastercard'
61 | | 'diners'
62 | | 'amex'
63 | | 'visa'
64 | | 'american-express'
65 | | 'diners-club'
66 | | 'discover'
67 | | 'jcb'
68 | | 'unionpay'
69 | | 'maestro'
70 | | 'elo'
71 | | 'mir'
72 | | 'hiper'
73 | | 'hipercard';
74 |
75 | export interface TextInputDatetimeOptions {
76 | format?: string;
77 | }
78 |
79 | export interface TextInputCreditCardOptions {
80 | obfuscated?: boolean;
81 | issuer?: SupportedCreditCardIssuers;
82 | }
83 |
84 | export interface TextInputCustomMaskOptions {
85 | mask?: string;
86 | validator?: (value: string, settings: TextInputMaskOptionProp) => boolean;
87 | getRawValue?: (value: string, settings: TextInputMaskOptionProp) => any;
88 | translation?: { [s: string]: (val: string) => string | null | undefined };
89 | }
90 |
91 | // Option prop of TextInputMask.
92 | export type TextInputMaskOptionProp = TextInputOptionBaseInterface &
93 | TextInputMoneyMaskOptions &
94 | TextInputDatetimeOptions &
95 | TextInputCreditCardOptions &
96 | TextInputPhoneOptions &
97 | TextInputCustomMaskOptions;
98 |
99 | export interface TextInputOptionBaseInterface {}
100 |
101 | type TextInputPropsWithoutValue = Pick<
102 | TextInputProps,
103 | Exclude
104 | >;
105 | // TextInputMask Props
106 | export interface TextInputMaskProps<
107 | Options extends TextInputOptionBaseInterface = TextInputMaskOptionProp
108 | > extends Pick<
109 | TextInputProps,
110 | Exclude
111 | > {
112 | type: TextInputMaskTypeProp;
113 | options?: Options;
114 | checkText?: (previous: ValueType, next: ValueType) => boolean;
115 | onChangeText?: (maskedText: ValueType, rawValue: number) => void;
116 | refInput?: Ref;
117 | customTextInput?: any;
118 | value: ValueType;
119 | }
120 |
121 | // TextMaskMethods
122 | interface TextMaskMethods {
123 | getElement(): TextInput;
124 | }
125 |
126 | // TextMaskInstance
127 | export type TextMaskInstance = TextMaskMethods | null;
128 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-masked-input",
3 | "version": "2.2.3",
4 | "description": "Text and TextInput with mask for React Native applications",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/src/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "react-native-masked-input.podspec",
17 | "!lib/typescript/example",
18 | "!**/__tests__",
19 | "!**/__fixtures__",
20 | "!**/__mocks__"
21 | ],
22 | "scripts": {
23 | "test": "jest",
24 | "typescript": "tsc --noEmit",
25 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
26 | "prepare": "bob build",
27 | "release": "dotenv release-it",
28 | "example": "yarn --cwd example",
29 | "pods": "cd example && pod-install --quiet",
30 | "bootstrap": "yarn example && yarn && yarn pods"
31 | },
32 | "keywords": [
33 | "react-native",
34 | "ios",
35 | "android"
36 | ],
37 | "repository": "https://github.com/thevsstech/react-native-masked-input",
38 | "author": "thevsstech (https://thevss.tech)",
39 | "license": "MIT",
40 | "bugs": {
41 | "url": "https://github.com/thevsstech/react-native-masked-input/issues"
42 | },
43 | "homepage": "https://github.com/thevsstech/react-native-masked-input#readme",
44 | "devDependencies": {
45 | "@commitlint/config-conventional": "^8.3.4",
46 | "@react-native-community/bob": "^0.16.2",
47 | "@react-native-community/eslint-config": "^2.0.0",
48 | "@release-it/conventional-changelog": "^1.1.4",
49 | "@types/jest": "^26.0.0",
50 | "@types/react": "^16.9.19",
51 | "@types/react-native": "0.62.13",
52 | "commitlint": "^8.3.5",
53 | "dotenv-cli": "^4.0.0",
54 | "eslint": "^7.2.0",
55 | "eslint-config-prettier": "^6.11.0",
56 | "eslint-plugin-prettier": "^3.1.3",
57 | "husky": "^4.2.5",
58 | "jest": "^26.0.1",
59 | "pod-install": "^0.1.0",
60 | "prettier": "^2.0.5",
61 | "react": "16.11.0",
62 | "react-native": "0.62.2",
63 | "release-it": "^13.5.8",
64 | "typescript": "^3.8.3"
65 | },
66 | "peerDependencies": {
67 | "react": "*",
68 | "react-native": "*"
69 | },
70 | "dependencies": {
71 | "credit-card-type": "^8.2.0",
72 | "date-and-time": "0.9.0",
73 | "tinymask": "1.0.2"
74 | },
75 | "jest": {
76 | "preset": "react-native",
77 | "modulePathIgnorePatterns": [
78 | "/example/node_modules",
79 | "/lib/"
80 | ]
81 | },
82 | "husky": {
83 | "hooks": {
84 | "pre-commit": "yarn lint && yarn typescript"
85 | }
86 | },
87 | "commitlint": {
88 | "extends": [
89 | "@commitlint/config-conventional"
90 | ]
91 | },
92 | "release-it": {
93 | "git": {
94 | "commitMessage": "chore: release ${version}",
95 | "tagName": "v${version}"
96 | },
97 | "npm": {
98 | "publish": true
99 | },
100 | "github": {
101 | "release": true
102 | },
103 | "plugins": {
104 | "@release-it/conventional-changelog": {
105 | "preset": "angular"
106 | }
107 | }
108 | },
109 | "eslintConfig": {
110 | "extends": [
111 | "@react-native-community",
112 | "prettier"
113 | ],
114 | "rules": {
115 | "prettier/prettier": [
116 | "error",
117 | {
118 | "quoteProps": "consistent",
119 | "singleQuote": true,
120 | "tabWidth": 2,
121 | "trailingComma": "es5",
122 | "useTabs": false
123 | }
124 | ]
125 | }
126 | },
127 | "eslintIgnore": [
128 | "node_modules/",
129 | "lib/"
130 | ],
131 | "prettier": {
132 | "quoteProps": "consistent",
133 | "singleQuote": true,
134 | "tabWidth": 2,
135 | "trailingComma": "es5",
136 | "useTabs": false
137 | },
138 | "@react-native-community/bob": {
139 | "source": "src",
140 | "output": "lib",
141 | "targets": [
142 | "commonjs",
143 | "module",
144 | "typescript"
145 | ]
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/src/masks/money.mask.js:
--------------------------------------------------------------------------------
1 | import BaseMask from './_base.mask';
2 | import VanillaMasker from '../internal-dependencies/vanilla-masker';
3 |
4 | const MONEY_MASK_SETTINGS = {
5 | precision: 2,
6 | separator: ',',
7 | delimiter: '.',
8 | unit: 'R$',
9 | suffixUnit: '',
10 | };
11 |
12 | export default class MoneyMask extends BaseMask {
13 | static getType() {
14 | return 'money';
15 | }
16 |
17 | getValue(value, settings) {
18 | const mergedSettings = super.mergeSettings(MONEY_MASK_SETTINGS, settings);
19 |
20 | const raw = this.getRawValueForMask(value, mergedSettings);
21 |
22 | // empty content should return empty string
23 | if (raw === '') {
24 | return '';
25 | }
26 |
27 | return VanillaMasker.toMoney(raw, mergedSettings);
28 | }
29 |
30 | handleInit(maskedValue, settings) {
31 | const opts = super.mergeSettings(MONEY_MASK_SETTINGS, settings);
32 |
33 | return this.includeSuffix(maskedValue, opts);
34 | }
35 |
36 | handleBlur(maskedValue, settings) {
37 | const opts = super.mergeSettings(MONEY_MASK_SETTINGS, settings);
38 |
39 | return this.includeSuffix(maskedValue, opts);
40 | }
41 |
42 | includeSuffix(maskedValue, opts) {
43 | const includeSuffix = opts.suffixUnit ? opts.suffixUnit : '';
44 | let { maskedText, rawText } = {
45 | maskedText: this.clearSuffix(maskedValue, includeSuffix, opts.unit),
46 | rawText: this.getRawValue(maskedValue, opts),
47 | };
48 | maskedText = this.getValue(maskedText, opts);
49 | maskedText = `${maskedText}${includeSuffix}`;
50 | return { maskedText, rawText };
51 | }
52 |
53 | handleChange(value, settings) {
54 | const opts = super.mergeSettings(MONEY_MASK_SETTINGS, {
55 | ...settings,
56 | zeroCents: false,
57 | });
58 |
59 | if (value === undefined || value === null) {
60 | return { maskedText: '', rawText: 0 };
61 | }
62 | let maskedText = this.getValue(value, opts);
63 | return { maskedText, rawText: this.getRawValue(maskedText) };
64 | }
65 |
66 | clearSuffix(value, suffixUnit, unit) {
67 | if (typeof value === 'number' || suffixUnit === '') {
68 | return value;
69 | }
70 |
71 | let position = value.replace(unit, '').indexOf(suffixUnit);
72 |
73 | const includes = position > 0;
74 |
75 | return includes ? value.slice(0, position + 1) : value;
76 | }
77 |
78 | handleFocus(maskedValue, settings) {
79 | const opts = super.mergeSettings(MONEY_MASK_SETTINGS, {
80 | ...settings,
81 | zeroCents: false,
82 | });
83 |
84 | if (typeof maskedValue === 'number') {
85 | return {
86 | maskedText: maskedValue === 0 ? '' : this.getValue(maskedValue, opts),
87 | rawText: maskedValue,
88 | };
89 | }
90 |
91 | const rawValue = this.getRawValue(maskedValue, opts);
92 |
93 | return {
94 | maskedText: maskedValue,
95 | rawText: rawValue,
96 | };
97 | }
98 |
99 | normalizeValue(maskedValue, settings) {
100 | if (typeof maskedValue === 'number') {
101 | return maskedValue;
102 | }
103 |
104 | const mergedSettings = super.mergeSettings(MONEY_MASK_SETTINGS, settings);
105 | const cleaned = super
106 | .removeNotNumbersForMoney(maskedValue)
107 | .toString()
108 | .split(mergedSettings.separator);
109 |
110 | // if seperator and delimeter are the same we cannot use the way we did before
111 | // this should not happen but if happens for some reason we will try to find decimals
112 | if (mergedSettings.separator === mergedSettings.delimiter) {
113 | if (cleaned.length === 1) {
114 | return cleaned[0];
115 | }
116 |
117 | const lastPart = cleaned.pop();
118 | const isLastPartDecimal = lastPart.length <= mergedSettings.precision;
119 |
120 | return cleaned.join('') + (isLastPartDecimal ? '.' + lastPart : lastPart);
121 | }
122 |
123 | return cleaned.join('').replace(mergedSettings.delimiter, '.');
124 | }
125 |
126 | getRawValueForMask(maskedValue, settings) {
127 | const normalized = this.normalizeValue(maskedValue, settings);
128 |
129 | if (normalized === '') {
130 | return '';
131 | }
132 |
133 | return normalized;
134 | }
135 |
136 | getRawValue(maskedValue, settings) {
137 | const mergedSettings = super.mergeSettings(MONEY_MASK_SETTINGS, settings);
138 | const normalized = this.normalizeValue(maskedValue, mergedSettings);
139 | return Number(normalized);
140 | }
141 |
142 | validate(value, settings) {
143 | return true;
144 | }
145 |
146 | _sanitize(value, settings) {
147 | if (typeof value === 'number') {
148 | return value.toFixed(settings.precision);
149 | }
150 |
151 | return value;
152 | }
153 |
154 | _insert(text, index, string) {
155 | if (index > 0) {
156 | return (
157 | text.substring(0, index) + string + text.substring(index, text.length)
158 | );
159 | } else {
160 | return string + text;
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/text-input-mask.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | TextInput,
3 | Platform,
4 | NativeSyntheticEvent,
5 | TextInputFocusEventData,
6 | KeyboardTypeOptions,
7 | } from 'react-native';
8 | import BaseTextComponent from './base-text-component';
9 | import type {
10 | TextInputMaskProps,
11 | TextInputOptionBaseInterface,
12 | ValueType,
13 | } from './types';
14 | import type { ReactText, RefObject } from 'react';
15 | import React from 'react';
16 |
17 | type State = {
18 | focused: boolean;
19 | };
20 |
21 | export default class TextInputMask<
22 | Options extends TextInputOptionBaseInterface
23 | > extends BaseTextComponent, State> {
24 | _inputElement!: RefObject;
25 |
26 | constructor(props: TextInputMaskProps) {
27 | super(props);
28 |
29 | this._handleFocus = this._handleFocus.bind(this);
30 | this._handleBlur = this._handleBlur.bind(this);
31 | this._inputElement = React.createRef();
32 | this._onChangeText = this._onChangeText.bind(this);
33 |
34 | this.state = {
35 | focused: false,
36 | };
37 | }
38 |
39 | get getElement() {
40 | return this._inputElement;
41 | }
42 |
43 | setContent = (maskedText: ReactText, rawText: number) => {
44 | if (this.props.onChangeText) {
45 | this._trySetNativeProps(maskedText);
46 | this.props.onChangeText(maskedText, rawText);
47 | }
48 | };
49 |
50 | /**
51 | * if focused use handleFocus if available
52 | * @param value
53 | */
54 | getDisplayValueFor(value: ValueType) {
55 | if (this.state.focused && this._maskHandler.handleFocus) {
56 | const { maskedText } = this._maskHandler.handleFocus(
57 | this._getDefaultValue(this.props.value),
58 | this.props.options
59 | );
60 |
61 | return maskedText;
62 | }
63 |
64 | return this._maskHandler.handleBlur
65 | ? this._maskHandler.handleBlur(
66 | this._getDefaultValue(this.props.value),
67 | this.props.options
68 | ).maskedText
69 | : this._handleChange(value).maskedText;
70 | }
71 |
72 | _handleChange(text: ValueType) {
73 | return this._maskHandler.handleChange
74 | ? this._maskHandler.handleChange(
75 | this._getDefaultValue(text),
76 | this._getOptions()
77 | )
78 | : this.updateValue(text);
79 | }
80 |
81 | _onChangeText(text: string) {
82 | if (!this._checkText(text)) {
83 | return;
84 | }
85 |
86 | const { maskedText, rawText } = this._handleChange(text);
87 |
88 | this.setContent(maskedText, rawText);
89 | }
90 |
91 | _handleBlur(e: NativeSyntheticEvent) {
92 | this.setState({
93 | focused: false,
94 | });
95 |
96 | if (this._maskHandler.handleBlur) {
97 | const { maskedText, rawText } = this._maskHandler.handleBlur(
98 | this._getDefaultValue(this.props.value),
99 | this.props.options
100 | );
101 |
102 | this.setContent(maskedText, rawText);
103 | }
104 |
105 | if (this.props.onBlur) {
106 | this.props.onBlur(e);
107 | }
108 | }
109 |
110 | _handleFocus(e: NativeSyntheticEvent) {
111 | this.setState({
112 | focused: true,
113 | });
114 |
115 | if (this._maskHandler.handleFocus) {
116 | const { maskedText, rawText } = this._maskHandler.handleFocus(
117 | this._getDefaultValue(this.props.value),
118 | this.props.options
119 | );
120 | this.setContent(maskedText, rawText);
121 | }
122 |
123 | if (this.props.onFocus) {
124 | this.props.onFocus(e);
125 | }
126 | }
127 |
128 | _trySetNativeProps(maskedText: ValueType) {
129 | if (typeof maskedText === 'number') {
130 | maskedText = maskedText.toString();
131 | }
132 | try {
133 | const element = this.getElement;
134 |
135 | element.current?.setNativeProps &&
136 | element.current.setNativeProps({ text: maskedText });
137 | } catch (error) {
138 | // silent
139 | }
140 | }
141 |
142 | _checkText(text: ValueType) {
143 | if (this.props.checkText) {
144 | return this.props.checkText(this.props.value, text);
145 | }
146 |
147 | return true;
148 | }
149 |
150 | _getKeyboardType() {
151 | return (
152 | this.props.keyboardType ||
153 | (this._maskHandler.getKeyboardType
154 | ? this._maskHandler.getKeyboardType()
155 | : 'default')
156 | );
157 | }
158 |
159 | render() {
160 | let Input = TextInput;
161 |
162 | if (this.props.customTextInput) {
163 | Input = this.props.customTextInput;
164 | }
165 |
166 | let displayValue = this.getDisplayValueFor(this.props.value);
167 |
168 | return (
169 |
182 | );
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn bootstrap` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn bootstrap
11 | ```
12 |
13 | While developing, you can run the [example app](/example/) to test your changes.
14 |
15 | To start the packager:
16 |
17 | ```sh
18 | yarn example start
19 | ```
20 |
21 | To run the example app on Android:
22 |
23 | ```sh
24 | yarn example android
25 | ```
26 |
27 | To run the example app on iOS:
28 |
29 | ```sh
30 | yarn example ios
31 | ```
32 |
33 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
34 |
35 | ```sh
36 | yarn typescript
37 | yarn lint
38 | ```
39 |
40 | To fix formatting errors, run the following:
41 |
42 | ```sh
43 | yarn lint --fix
44 | ```
45 |
46 | Remember to add tests for your change if possible. Run the unit tests by:
47 |
48 | ```sh
49 | yarn test
50 | ```
51 |
52 | To edit the Objective-C files, open `example/ios/MaskedInputExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-masked-input`.
53 |
54 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativemaskedinput` under `Android`.
55 |
56 | ### Commit message convention
57 |
58 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
59 |
60 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
61 | - `feat`: new features, e.g. add new method to the module.
62 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
63 | - `docs`: changes into documentation, e.g. add usage example for the module..
64 | - `test`: adding or updating tests, eg add integration tests using detox.
65 | - `chore`: tooling changes, e.g. change CI config.
66 |
67 | Our pre-commit hooks verify that your commit message matches this format when committing.
68 |
69 | ### Linting and tests
70 |
71 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
72 |
73 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
74 |
75 | Our pre-commit hooks verify that the linter and tests pass when committing.
76 |
77 | ### Scripts
78 |
79 | The `package.json` file contains various scripts for common tasks:
80 |
81 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
82 | - `yarn typescript`: type-check files with TypeScript.
83 | - `yarn lint`: lint files with ESLint.
84 | - `yarn test`: run unit tests with Jest.
85 | - `yarn example start`: start the Metro server for the example app.
86 | - `yarn example android`: run the example app on Android.
87 | - `yarn example ios`: run the example app on iOS.
88 |
89 | ### Sending a pull request
90 |
91 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).
92 |
93 | When you're sending a pull request:
94 |
95 | - Prefer small pull requests focused on one change.
96 | - Verify that linters and tests are passing.
97 | - Review the documentation to make sure it looks good.
98 | - Follow the pull request template when opening a pull request.
99 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
100 |
101 | ## Code of Conduct
102 |
103 | ### Our Pledge
104 |
105 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
106 |
107 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
108 |
109 | ### Our Standards
110 |
111 | Examples of behavior that contributes to a positive environment for our community include:
112 |
113 | - Demonstrating empathy and kindness toward other people
114 | - Being respectful of differing opinions, viewpoints, and experiences
115 | - Giving and gracefully accepting constructive feedback
116 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
117 | - Focusing on what is best not just for us as individuals, but for the overall community
118 |
119 | Examples of unacceptable behavior include:
120 |
121 | - The use of sexualized language or imagery, and sexual attention or
122 | advances of any kind
123 | - Trolling, insulting or derogatory comments, and personal or political attacks
124 | - Public or private harassment
125 | - Publishing others' private information, such as a physical or email
126 | address, without their explicit permission
127 | - Other conduct which could reasonably be considered inappropriate in a
128 | professional setting
129 |
130 | ### Enforcement Responsibilities
131 |
132 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
133 |
134 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
135 |
136 | ### Scope
137 |
138 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
139 |
140 | ### Enforcement
141 |
142 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
143 |
144 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
145 |
146 | ### Enforcement Guidelines
147 |
148 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
149 |
150 | #### 1. Correction
151 |
152 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
153 |
154 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
155 |
156 | #### 2. Warning
157 |
158 | **Community Impact**: A violation through a single incident or series of actions.
159 |
160 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
161 |
162 | #### 3. Temporary Ban
163 |
164 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
165 |
166 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
167 |
168 | #### 4. Permanent Ban
169 |
170 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
171 |
172 | **Consequence**: A permanent ban from any sort of public interaction within the community.
173 |
174 | ### Attribution
175 |
176 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
177 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
178 |
179 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
180 |
181 | [homepage]: https://www.contributor-covenant.org
182 |
183 | For answers to common questions about this code of conduct, see the FAQ at
184 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
185 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | a# react-native-masked-input
2 |
3 | 
4 | [](https://www.codetriage.com/thevsstech/react-native-masked-input)
5 |
6 | This is a simple masked text (normal text and input text) component for React-Native.
7 |
8 | ## Alert
9 | Hey guys!
10 |
11 | The old repository [react-native-masked-input](https://github.com/benhurott/react-native-masked-input) is no longer maintained and because I actively use masked input I deciced to maintain this repository here.
12 |
13 |
14 | ## Supported Versions
15 |
16 | React-native: 0.32.0 or higher
17 |
18 | ## Install
19 |
20 | `npm install react-native-masked-input --save`
21 |
22 | or with yarn
23 |
24 | `yarn add react-native-masked-input`
25 |
26 | ## Usage (TextInputMask)
27 |
28 | For all the masks you will use in this way:
29 |
30 | ```jsx
31 | import TextInputMask from 'react-native-masked-input'
32 | // for backwards compatibility old import syntax is allowed as;
33 | // import {TextInputMask} from 'react-native-masked-input'
34 |
35 | //...
36 |
37 | {
48 | this.setState({
49 | text: text
50 | })
51 | }}
52 | />
53 | ```
54 |
55 | ### Cel Phone
56 |
57 | Mask:
58 |
59 | - BRL (default): `(99) 9999-9999` or `(99) 99999-9999` (will detect automatically)
60 | - INTERNATIONAL: `+999 999 999 999`
61 |
62 | If you need a different formatting, use the `Custom` mask =).
63 |
64 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/CelPhone.js)):
65 |
66 | ```jsx
67 | {
76 | this.setState({
77 | international: text
78 | })
79 | }}
80 | />
81 | ```
82 | #### Options
83 |
84 | | name | type | required | default | description |
85 | | ---------- | ------- | -------- | ------- | ----------- |
86 | | maskType | string | no | `maskType` | the type of the mask to use. Available: `BRL` or `INTERNATIONAL` |
87 | | withDDD | boolean | no | `true` | if the mask type is `BRL`, include the DDD |
88 | | dddMask | string | no | `(99) ` | if the mask type is `BRL`, the DDD mask |
89 |
90 | #### Methods
91 |
92 | You can get the `unmasked` value using the `getRawValue` method:
93 |
94 | ```jsx
95 | {
104 | this.setState({
105 | international: text
106 | })
107 | }}
108 | // add the ref to a local var
109 | ref={(ref) => this.phoneField = ref}
110 | />
111 |
112 | //...
113 |
114 | const unmasked = this.phoneField.getRawValue()
115 | // in the mask: (51) 98765-4321
116 | // unmasked: 51987654321
117 | ```
118 |
119 |
120 | ### CPF
121 |
122 | Mask: `999.999.999-99`
123 |
124 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/Cpf.js)):
125 |
126 | ```jsx
127 | {
131 | this.setState({
132 | cpf: text
133 | })
134 | }}
135 | />
136 | ```
137 |
138 | #### Methods
139 |
140 | You can check if the cpf is valid by calling the `isValid()` method:
141 |
142 | ```jsx
143 | {
147 | this.setState({
148 | cpf: text
149 | })
150 | }}
151 | // add the ref to a local var
152 | ref={(ref) => this.cpfField = ref}
153 | />
154 |
155 | // get the validation
156 |
157 | const cpfIsValid = this.cpfField.isValid()
158 | console.log(cpfIsValid) // boolean
159 | ```
160 |
161 | You can get the `unmasked` cpf calling the `getRawValue` method:
162 |
163 | ```jsx
164 | const unmasked = this.cpfField.getRawValue()
165 | // in the mask: 123.456.789-01
166 | // unmasked: 12345678901
167 | ```
168 |
169 | ### CNPJ
170 |
171 | Mask: `99.999.999/9999-99`
172 |
173 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/Cnpj.js)):
174 |
175 | ```jsx
176 | {
180 | this.setState({
181 | cnpj: text
182 | })
183 | }}
184 | />
185 | ```
186 |
187 | #### Methods
188 |
189 | You can check if the cnpj is valid by calling the `isValid()` method:
190 |
191 | ```jsx
192 | {
196 | this.setState({
197 | cnpj: text
198 | })
199 | }}
200 | // add the ref to a local var
201 | ref={(ref) => this.cnpjField = ref}
202 | />
203 |
204 | // get the validation
205 |
206 | const cnpjIsValid = this.cnpjField.isValid()
207 | console.log(cnpjIsValid) // boolean
208 | ```
209 |
210 |
211 | You can get the `unmasked` cpf calling the `getRawValue` method:
212 |
213 | ```jsx
214 | const unmasked = this.cnpjField.getRawValue()
215 | // in the mask: 99.999.999/9999-99
216 | // unmasked: 99999999999999
217 | ```
218 |
219 | ### Credit Card
220 |
221 | Mask:
222 |
223 | - visa or master: `9999 9999 9999 9999` or `9999 **** **** 9999` (obfuscated)
224 | - amex: `9999 999999 99999` or `9999 ****** 99999` (obfuscated)
225 | - diners: `9999 999999 9999` or `9999 ****** 9999` (obfuscated)
226 |
227 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/CreditCard.js))
228 |
229 | ```jsx
230 | {
238 | this.setState({
239 | creditCard: text
240 | })
241 | }}
242 | />
243 | ```
244 |
245 | #### Options
246 |
247 | | name | type | required | default | description |
248 | | ---------- | ------- | -------- | -------------------- | ----------- |
249 | | obfuscated | boolean | no | `false` | if the mask should be obfuscated or not|
250 | | issuer | string | no | `visa-or-mastercard` | the type of the card mask. The options are: `visa-or-mastercard`, `amex` or `diners` |
251 |
252 |
253 | #### Methods
254 |
255 | You can get the array containing the groups of the value value using the `getRawValue` method:
256 |
257 | ```jsx
258 | {
266 | this.setState({
267 | creditCard: text
268 | })
269 | }}
270 | // add the ref to a local var
271 | ref={(ref) => this.creditCardField = ref}
272 | />
273 |
274 | //...
275 |
276 | const unmasked = this.creditCardField.getRawValue()
277 | // in the mask: 9874 6541 3210 9874
278 | // unmasked: [9874, 6541, 3210, 9874]
279 | ```
280 |
281 | ### Custom
282 |
283 | Mask: `defined by pattern`
284 |
285 | * `9` - accept digit.
286 | * `A` - accept alpha.
287 | * `S` - accept alphanumeric.
288 | * `*` - accept all, EXCEPT white space.
289 |
290 | Ex: `AAA-9999`
291 |
292 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/Custom.js)):
293 |
294 | ```jsx
295 | //
296 | // SIMPLE
297 | //
298 | {
313 | this.setState({
314 | text: text
315 | })
316 | }}
317 | style={textInputStype}
318 | />
319 |
320 |
321 | //
322 | // ADVANCED
323 | //
324 | = 0 ? val : null;
378 | }
379 | }
380 | }}
381 | value={this.state.text}
382 | onChangeText={text => {
383 | this.setState({
384 | text: text
385 | })
386 | }}
387 | style={textInputStype}
388 | />
389 | ```
390 |
391 | #### Options
392 |
393 | | name | type | required | default | description |
394 | | ---------- | ------- | -------- | -------------------- | ----------- |
395 | | mask | string | **YES** | | The mask pattern |
396 | | validator | function | no | function that returns `true` | the function that's validate the value in the mask |
397 | | getRawValue | function | no | return current value | function to parsed value (like unmasked or converted) |
398 | | translation | object (map{string,function}) | no | `9 - digit`, `A - alpha`, `S - alphanumeric`, `* - all, except space` | The translator to use in the pattern |
399 |
400 |
401 | ### Datetime
402 |
403 | Mask:
404 |
405 | * `DD/MM/YYYY HH:mm:ss`
406 | * `DD/MM/YYYY`
407 | * `MM/DD/YYYY`
408 | * `YYYY/MM/DD`
409 | * `HH:mm:ss`
410 | * `HH:mm`
411 | * `HH`
412 |
413 | You can use `-` instead of `/` if you want.
414 |
415 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/Datetime.js)):
416 |
417 | ```jsx
418 | {
425 | this.setState({
426 | dt: text
427 | })
428 | }}
429 | />
430 | ```
431 |
432 | #### Options
433 |
434 | | name | type | required | default | description |
435 | | ---------- | ------- | -------- | -------------------- | ----------- |
436 | | format | string | **YES** | | The date format to be validated |
437 |
438 |
439 | #### Methods
440 |
441 | You can check if the date is valid by calling the `isValid()` method:
442 |
443 | ```jsx
444 | {
451 | this.setState({
452 | dt: text
453 | })
454 | }}
455 | // add the ref to a local var
456 | ref={(ref) => this.datetimeField = ref}
457 | />
458 |
459 | // get the validation
460 |
461 | const isValid = this.datetimeField.isValid()
462 | console.log(isValid) // boolean
463 | ```
464 |
465 | You can get the [moment](https://momentjs.com/) object from the date if it's valid calling the `getRawValue` method:
466 |
467 | ```jsx
468 | const momentDate = this.datetimeField.getRawValue()
469 | ```
470 |
471 | ### Money
472 |
473 | Mask: `R$999,99` (fully customizable)
474 |
475 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/Money.js)):
476 |
477 | ```jsx
478 | // SIMPLE
479 | {
483 | this.setState({
484 | simple: text
485 | })
486 | }}
487 | />
488 |
489 | // ADVANCED
490 | {
501 | this.setState({
502 | advanced: text
503 | })
504 | }}
505 | />
506 | ```
507 |
508 | #### Options
509 |
510 | | name | type | required | default | description |
511 | | ---------- | ------- | -------- | -------------------- | ----------- |
512 | | precision | number | no | `2` | The number of cents to show |
513 | | separator | string | no | `,` | The cents separator |
514 | | delimiter | string | no | `.` | The thousand separator |
515 | | unit | string | no | `R$` | The prefix text |
516 | | suffixUnit | string | no | `''` | The sufix text |
517 | | zeroCents | boolean | no | false | whether you want to fill your value with zero cents, for example, if you provide 1000 it will become 1000,00
518 |
519 | #### Methods
520 |
521 | You can get the `number` value of the mask calling the `getRawValue` method:
522 |
523 | ```jsx
524 | {
528 | this.setState({
529 | simple: text
530 | })
531 | }}
532 | // add the ref to a local var
533 | ref={(ref) => this.moneyField = ref}
534 | />
535 |
536 | const numberValue = this.moneyField.getRawValue()
537 | console.log(numberValue) // Number
538 |
539 | // CAUTION: the javascript do not support giant numbers.
540 | // so, if you have a big number in this mask, you could have problems with the value...
541 | ```
542 | ### Only Numbers
543 |
544 | Mask: `accept only numbers`
545 |
546 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/OnlyNumbers.js)):
547 |
548 |
549 | ```jsx
550 | {
554 | this.setState({
555 | value: text
556 | })
557 | }}
558 | />
559 | ```
560 |
561 | ```
562 |
563 |
564 | ### Only Letters
565 |
566 | Mask: `accept only numbers`
567 |
568 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/OnlyNumbers.js)):
569 |
570 |
571 | ```jsx
572 | {
576 | this.setState({
577 | value: text
578 | })
579 | }}
580 | />
581 | ```
582 |
583 | ### Zip Code
584 |
585 | Mask: `99999-999`
586 |
587 | Sample code ([source](https://github.com/benhurott/react-native-masked-input-samples/blob/master/ReactNativeMaskedTextSamples/Samples/OnlyNumbers.js)):
588 |
589 |
590 | ```jsx
591 | {
595 | this.setState({
596 | value: text
597 | })
598 | }}
599 | />
600 | ```
601 |
602 | #### Methods
603 |
604 | You can get the `unmasked` value using the `getRawValue` method:
605 |
606 | ```jsx
607 | {
611 | this.setState({
612 | value: text
613 | })
614 | }}
615 | // add the ref to a local var
616 | ref={(ref) => this.zipCodeField = ref}
617 | />
618 |
619 | //...
620 |
621 | const unmasked = this.zipCodeField.getRawValue()
622 | // in the mask: 98765-321
623 | // unmasked: 98765321
624 | ```
625 |
626 | ### ... Utils
627 |
628 | #### Including the `rawText` in `onChangeText` [1.12.0+]
629 |
630 | From [2.0.0+] raw text automatically included onChangeText calls
631 |
632 | ```jsx
633 | {
638 | // maskedText: 123.456.789-01
639 | // rawText: 12345678901
640 | }}
641 | />
642 | ```
643 |
644 |
645 | #### Getting the `TextInput` instance
646 | If you want to get the `TextInput` raw component, use the `getElement()` method:
647 |
648 | ```jsx
649 | {
653 | this.setState({
654 | value: text
655 | })
656 | }}
657 | // add the ref to a local var
658 | ref={(ref) => this.zipCodeField = ref}
659 | />
660 |
661 | //...
662 |
663 | const textInput = this.zipCodeField.getElement()
664 | ```
665 |
666 | #### Blocking user to add character
667 |
668 | If you want, you can block a value to be added to the text using the `checkText` prop:
669 |
670 | ```jsx
671 | {
680 | return next === 'your valid value or other boolean condition';
681 | }
682 | }
683 | />
684 | ```
685 |
686 | #### Using custom text inputs
687 |
688 | You can use this prop if you want custom text input instead native TextInput component:
689 |
690 | ```jsx
691 | const Textfield = MKTextField.textfield()
692 | .withPlaceholder('Text...')
693 | .withStyle(styles.textfield)
694 | .build();
695 |
696 |
697 |
703 | ```
704 |
705 | #### About the normal text input props
706 |
707 | You can use all the normal TextInput props from React-Native, with this in mind:
708 |
709 | - onChangeText is intercepted by component.
710 | - value is intercepted by component.
711 | - if you pass keyboardType, it will override the keyboardType of masked component.
712 |
713 | #### Code Samples
714 |
715 | If you want, you can check the code samples in this repo:
716 |
717 | [react-native-masked-input-samples](https://github.com/benhurott/react-native-masked-input-samples)
718 |
719 | ## Usage (TextMask)
720 |
721 | ```jsx
722 | import React, { Component } from 'react'
723 |
724 | // import the component
725 | import { TextMask } from 'react-native-masked-input'
726 |
727 | export default class MyComponent extends Component {
728 | constructor(props) {
729 | super(props)
730 | this.state = {
731 | text: '4567123409871234'
732 | }
733 | }
734 |
735 | render() {
736 | // the type is required but options is required only for some specific types.
737 | // the sample below will output 4567 **** **** 1234
738 | return (
739 |
746 | )
747 | }
748 | }
749 | ```
750 |
751 | ### Props
752 |
753 | The same of _TextInputMask_, but for React-Native _Text_ component instead _TextInput_.
754 |
755 | _Warning_: if the value not match the mask, it will not appear.
756 |
757 | ### Methods
758 |
759 | `getElement()`: return the instance of _Text_ component.
760 |
761 | ## Extra (MaskService)
762 |
763 | If you want, we expose the `MaskService`. You can use it:
764 |
765 | **Methods**
766 |
767 | - static toMask(type, value, settings): mask a value.
768 | - `type` (String, required): the type of the mask (`cpf`, `datetime`, etc...)
769 | - `value` (String, required): the value to be masked
770 | - `settings` (Object, optional): if the mask type accepts options, pass it in the settings parameter
771 | - static toRawValue(type, maskedValue, settings): get the raw value of a masked value.
772 | - `type` (String, required): the type of the mask (`cpf`, `datetime`, etc...)
773 | - `maskedValue` (String, required): the masked value to be converted in raw value
774 | - `settings` (Object, optional): if the mask type accepts options, pass it in the settings parameter
775 | - static isValid(type, value, settings): validate if the mask and the value match.
776 | - `type` (String, required): the type of the mask (`cpf`, `datetime`, etc...)
777 | - `value` (String, required): the value to be masked
778 | - `settings` (Object, optional): if the mask type accepts options, pass it in the settings parameter
779 | - static getMask(type, value, settings): get the mask used to mask the value
780 |
781 | Ex:
782 |
783 | ```jsx
784 | import { MaskService } from 'react-native-masked-input'
785 |
786 | var money = MaskService.toMask('money', '123', {
787 | unit: 'US$',
788 | separator: '.',
789 | delimiter: ','
790 | })
791 |
792 | // money -> US$ 1.23
793 | ```
794 |
795 | ## Throubleshooting
796 |
797 | - If the `es2015` error throw by babel, try run `react-native start --reset-cache`
798 |
799 | ## Changelog
800 |
801 | View changelog [HERE](CHANGELOG.md)
802 |
803 | ## Thanks to
804 |
805 | -
806 |
807 | - Thanks to [vanilla-masker](https://github.com/BankFacil/vanilla-masker) =).
808 | - Thanks to [moment](http://momentjs.com/) =).
809 | - Thanks to [benhurott](https://github.com/benhurott) for this awesome project
810 |
--------------------------------------------------------------------------------