实现边输入边校验是否符合限制规则,如果不符合使得这一行的字符颜色为红
<style scoped>
.main {
width: 500px;
margin-left: 100px;
height: 500px;
position: relative;
}
.common-style {
width: 100%;
height: 100%;
font-size: 14px;
font-family: monospace;
word-break: break-all;
letter-spacing: 1px; /* 设置字间距 */
line-height: 1.5715;
}
/* div */
.highlight-shadow-input {
position: absolute;
top: 0;
left: 0;
margin-left: -100px;
padding: 9px;
border: 1px;
box-sizing: border-box;
overflow: auto;
white-space: pre-wrap;
text-align: left;
vertical-align: bottom;
z-index: 0;
}
.highlight-input {
position: relative;
padding: 5px 11px;
display: block;
margin-left: -100px;
padding: 8px;
box-sizing: border-box;
background: rgba(0, 0, 0, 0);
z-index: 999;
word-break: break-all;
resize: none;
}
.show-text {
-webkit-text-fill-color: transparent;
}
</style>
<style>
.vin-matching-error {
color: #ff4d4f;
position: relative;
z-index: 10000;
word-break: break-all;
font-size: 14px;
line-height: 1.5715;
}
</style>
<template>
<div style="padding: 50px">
<a-row>
<a-col :span="8">
<div class="main" >
<div
v-html="content"
class="highlight-shadow-input common-style"
spellcheck="false"
></div>
<a-textarea
v-model:value="vinStringq"
cols="30"
rows="10"
class="highlight-input common-style"
:class="{ 'show-text': vinStringq }"
@input="processInput"
@scroll="syncScroll"
spellcheck="false"
placeholder="请输入符合要求的数据。"
></a-textarea>
<span v-if="!isValid" style="color: red; margin-left: -50px; margin-top: 10px"
>请输入正确的 数据</span
>
</div>
</a-col>
</a-row>
</div>
</template>
<script setup>
import { ref } from 'vue';
const vinStringq = ref('');
const content = ref('');
const isValid = ref(true);
let syncScroll = (event) => {
let contentDivDom = document.querySelector('.highlight-shadow-input');
const scrollTop = event.target.scrollTop;
contentDivDom.scrollTop = scrollTop;
};
function processInput() {
const lines = vinStringq.value.split('\n');
//写正则表达式 此表达式限制每一行必须为17位字符,并且不含A/a字母
const regex = /^[B-Z0-9]{17}$/i;
let isAllValid = true;
let processedLines = lines.map((line) => {
const trimmedLine = line.replace(/\s/g, ''); // 去除空格
if (trimmedLine !== '' && (trimmedLine.length !== 17 || !regex.test(trimmedLine))) {
isAllValid = false;
return `<span style="color:#e52e2e">${line}</span>`;
} else {
return (!line ? `<span></span> `: line);
}
});
content.value = processedLines.join('<br>');
isValid.value = isAllValid;
}
</script>