Recently, while working with Vue 2.6, I came across an unusual issue when trying to sanitize user input.
The main culprit seemed to be a custom component that housed the input field. Here's a simplified version of it:
<template>
<input :name="name" :value="value" @input="(e) => onInput(e.target.value)" />
</template>
The onInput
function simply emits the input
event and both value
and name
are passed as props.
This component worked smoothly in most scenarios until I needed to filter out lowercase and whitespace characters from the input. To achieve this, I set up a watcher for the field
:
onFieldChange(field) {
this.field = field.replace(/[\sa-z]/gi, '')
}
After implementing this, I noticed a strange behavior where entering an invalid string like test
would appear as expected inside the input field, but upon closer inspection, the actual field
value was attached as an empty string due to filtering out the invalid characters. This discrepancy became more apparent when adding a valid character, like T
, resulting in the correct rendering as just T
.
It dawned on me that the root cause lay in the fact that my Field
component failed to recognize any changes in its props ('value' remained constant as an empty string), thus not triggering a re-render. Despite identifying the issue, I'm unsure about how to address it. Does anyone have any insights or possible solutions? Your help is much appreciated. Thanks!