Skip to content

Commit

Permalink
feat(createTextMask): adds allowEmpty option
Browse files Browse the repository at this point in the history
Closes #53
  • Loading branch information
Renato Böhler committed Nov 6, 2018
1 parent 0e01601 commit 07e713a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
20 changes: 18 additions & 2 deletions src/createTextMask.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default options => {
maskDefinitions = defaultMaskDefinitions,
guide = true,
stripMask = true,
allowEmpty = false,
onChange,
onCompletePattern,
} = options;
Expand Down Expand Up @@ -61,7 +62,14 @@ export default options => {

const format = (storeValue, calledFromNormalize = false) => {
if (!storeValue) {
return applyMask('', pattern, placeholder, guide, maskDefinitions);
return applyMask(
'',
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
);
}

if (!stripMask && !calledFromNormalize) {
Expand All @@ -70,7 +78,14 @@ export default options => {
}

// Format the mask according to pattern and maskDefinitions
return applyMask(storeValue, pattern, placeholder, guide, maskDefinitions);
return applyMask(
storeValue,
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
);
};

const normalize = (updatedValue, previousValue) => {
Expand All @@ -79,6 +94,7 @@ export default options => {
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
);

Expand Down
17 changes: 16 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,19 @@ const applyMask = (
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
) => {
let applied = '';

let value = !strippedValue ? '' : strippedValue;

/* If the value is empty, allowEmpty is set and guide is not, the formatted
value should be an empty string */
if (value.length === 0 && allowEmpty && !guide) {
return '';
}

// There are two indexes we need to control: value and pattern
let valueIndex = 0;

Expand Down Expand Up @@ -128,6 +135,7 @@ const inputReformat = (
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
) => {
let string = !inputString ? '' : inputString;
Expand All @@ -147,7 +155,14 @@ const inputReformat = (
const placeholderRegExp = escapeRegExp(placeholder);
string = string.replace(placeholderRegExp, '');

return applyMask(string, pattern, placeholder, guide, maskDefinitions);
return applyMask(
string,
pattern,
placeholder,
guide,
allowEmpty,
maskDefinitions,
);
};

/**
Expand Down

0 comments on commit 07e713a

Please sign in to comment.