Skip to content

Commit

Permalink
Fix #2214: KeyFilter prevent paste if regex not met (#2735)
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware authored Apr 14, 2022
1 parent fdb9f4a commit f128cf5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
11 changes: 9 additions & 2 deletions components/lib/inputtext/InputText.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ export const InputText = React.memo(React.forwardRef((props, ref) => {
}
}

const onPaste = (event) => {
if (props.keyfilter) {
KeyFilter.onPaste(event, props.keyfilter, props.validateOnly)
}
}

const isFilled = React.useMemo(() => (
ObjectUtils.isNotEmpty(props.value) || ObjectUtils.isNotEmpty(props.defaultValue) || (elementRef.current && ObjectUtils.isNotEmpty(elementRef.current.value))
), [props.value, props.defaultValue]);
Expand All @@ -45,7 +51,7 @@ export const InputText = React.memo(React.forwardRef((props, ref) => {

return (
<>
<input ref={elementRef} {...otherProps} className={className} onInput={onInput} onKeyPress={onKeyPress} />
<input ref={elementRef} {...otherProps} className={className} onInput={onInput} onKeyPress={onKeyPress} onPaste={onPaste} />
{hasTooltip && <Tooltip target={elementRef} content={props.tooltip} {...props.tooltipOptions} />}
</>
)
Expand All @@ -59,5 +65,6 @@ InputText.defaultProps = {
tooltip: null,
tooltipOptions: null,
onInput: null,
onKeyPress: null
onKeyPress: null,
onPaste: null
}
23 changes: 22 additions & 1 deletion components/lib/keyfilter/KeyFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,16 @@ export const KeyFilter = {
return e.charCode || e.keyCode || e.which;
},

getRegex(keyfilter) {
return KeyFilter.DEFAULT_MASKS[keyfilter] ? KeyFilter.DEFAULT_MASKS[keyfilter] : keyfilter;
},

onKeyPress(e, keyfilter, validateOnly) {
if (validateOnly) {
return;
}

const regex = KeyFilter.DEFAULT_MASKS[keyfilter] ? KeyFilter.DEFAULT_MASKS[keyfilter] : keyfilter;
const regex = this.getRegex(keyfilter);
const browser = DomHandler.getBrowser();

if (e.ctrlKey || e.altKey) {
Expand All @@ -88,6 +92,23 @@ export const KeyFilter = {
}
},

onPaste(e, keyfilter, validateOnly) {
if (validateOnly) {
return;
}

const regex = this.getRegex(keyfilter);
const clipboard = e.clipboardData.getData("text");

// loop over each letter pasted and if any fail prevent the paste
[...clipboard].forEach(c => {
if (!regex.test(c)) {
e.preventDefault();
return false;
}
});
},

validate(e, keyfilter) {
let value = e.target.value,
validatePattern = true;
Expand Down

0 comments on commit f128cf5

Please sign in to comment.