为两个字符定义一个正则表达式,然后定义两个数字



我正在我的 React 应用程序中使用正则表达式来验证表单条目的输入。输入使用 onChange 侦听器调用一个函数,该函数设置字符更改的状态。

有效输入是两个字符后跟两个数字。 即 RD01 或 EX12

我已经通过重新工作来检查它。它匹配正确的大小写,尽管它也仅适用于两位数。即 01 或 12

const onAssetChange = (e) => {
const input = e.target.value.toUpperCase()
const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
if (!input || input.match(re)) {
setAssetID(input)
}
}

正则表达式需要能够在每次击键时更新,因为它会更新每个更改事件的状态。

RegExp('^[A-Z]{0,2}[0-9]{0,2}$')将检查012字符。数字也是如此,因此即使A1也是有效的。请尝试以下操作:

const re = new RegExp('^[A-Z]{2}[0-9]{2}$')

您可以使用'^[A-Z][A-Z][0-9][0-9]$'.

这应该有效...

const onAssetChange = (e) => {
const input = e.target.value.toUpperCase()
const re = new RegExp('^w{2}d{2}$')
if (!input || input.match(re)) {
setAssetID(input)
}
}

好吧,所以它不漂亮...

const onAssetChange = (e) => {
const input = e.target.value.toUpperCase()
const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
if (!input || input.match(re) && (input.length < 2 ? input[0].match(/[A-Z]/) : input.slice(0,2).match(/[A-Z][A-Z]/)) ) {
setAssetID(input)
}
}

但它有效。如果有人有更优雅的解决方案,我很想听听。

尝试使用正则表达式[A-Z]{2}[0-9]{2}

正则表达式中的错误是{0,2}提供的字符集中 0 到 2 个元素的量词匹配。请改用{2}。这将断言检查恰好 2 个字符集计数。

我的建议是使用 mockFunction 将您的输入更新为 tme 所需的标准,如映射HI as HI00AA as AA00Aa as Aa00等,并测试这个模拟字符串。这是相同的示例。

console.log('R -- ', mockInput('R'));
console.log('RD --', mockInput('RD'));
console.log('RD0 -- ', mockInput('RD0'));
console.log('RD01 -- ', mockInput('RD01'));
console.log('01 -- ', mockInput('01'));
console.log('R01 -- ', mockInput('R01'));
console.log('RD011 -- ', mockInput('RD011'));
function mockInput(input) {
const returnStr = "AA00";
const fakeInput = input.length >= 4? input: input + returnStr.substring(input.length, 4);
const re = RegExp(/[A-Z]{2}[0-9]{2}/);
let status = false;
if (re.test(fakeInput)) {
status = true;
}
return status;
};

相关内容

最新更新