I am doing some url validations and I am getting a failure. It stops all the time after the 6th letter is typed. Below I am typing in "www.google.com" which is in a list of valid urls. However, it fails although it shouldn't.
例如:
w
ww
www
www.
www.g
www.go <-breaks here
www.goo <- continues to break
const validUrl = (value: string | null): string => {
let item: string
const regex = /^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})+(\.[a-zA-Z]{2,3})?((\/)?[a-z0-9-]{1,61}(\/)?){0,30}$/
if (value === null || value === '') {
return ''
}
if (value && typeof value === 'string' && !regex.test(value)) {
for (item in urlStrings) {
if (item.startsWith(value)) {
return ''
} else if (value.startsWith(item)) {
return ''
}
}
}
return 'Invalid url'
}
这是网址字符串:
export const urlStrings: { [key: string]: string } = {
'www.costco.com': '',
'www.walmart.com': '',
'www.google.com': '',
'www.facebook.com': '',
}
1条答案
按热度按时间oaxa6hgo1#
我在https://regex101.com/测试了你的正则表达式,它匹配
www.go
,但是,它不匹配www.g
,因为第一个\.
之后的所有组都需要至少两个字母(对于某些N
,{2,N}
)。可能是由于某种原因,你的代码在第一次失败后停止工作,并且不检查进一步的输入。但是,我无法运行你的代码并重现这个问题。
希望这对你有帮助。