简体   繁体   English

为什么正则表达式是“\d+(-\d+)?[AZ]?” 与 HTML5 模式属性中的字符串“180-186”不匹配?

[英]Why is the regex “\d+(-\d+)?[A-Z]?” not matching the string “180-186” in a HTML5 pattern attribute?

I have the following HTML5 form:我有以下 HTML5 表格:

<form id="address-form" method="POST">
    // ...other inputs that work fine

    <input type="text" name="street_number" class="form-control" placeholder="Street No.*" tabindex="3" required pattern="\d+(-\d+)?[A-Z]?" title="Please enter only digits separated by a single optional hyphen, with a single optional letter suffix.">
    <input type="text" name="street_address" class="form-control" placeholder="Address*" tabindex="4" required pattern="[A-z ]+" title="Please enter only letters and spaces.">

    // ...other inputs that work fine
</form>

And the following jQuery:以及以下 jQuery:

let form = $('#address-form');
form.find('[required]').each((i, elem) => {
    invalidElem = $(elem);

    // ...more unrelated code

    if (elem.name === 'password1' && elem.value !== '') {
        password = elem.value;
    }

    if (elem.name === 'password2') {
        elem.setCustomValidity(elem.value === password ? '' :
            'This field must match the password field.');
    }

    invalidElem.removeAttr('style');
    return (isValid = elem.reportValidity());
});

I am testing validation of the first input shown with the string "180-186" and it is failing.我正在测试使用字符串“180-186”显示的第一个输入的验证,但它失败了。 Why?为什么?

According to https://regex101.com/ this should work fine in JavaScript, which I assume is the regex engine used by browsers to validate pattern attributes...but Chrome (at least) seems to disprove that assumption, so if anyone definitively knows the actual regex engine used by browsers I'd love to know.根据https://regex101.com/这在 JavaScript 中应该可以正常工作,我认为这是浏览器用来验证pattern属性的正则表达式引擎......但是 Chrome(至少)似乎反驳了这个假设,所以如果有人明确知道我很想知道的浏览器使用的实际正则表达式引擎。

In case it's not obvious to anyone, this input needs to take the street number portion of an address.如果对任何人都不明显,则此输入需要采用地址的门牌号部分。 So "143", "22A", "180-186" and "1-7A" should all match, but having the letter anywhere but the end should not match, nor should anything with multiple hyphens, letters or any spaces.所以“143”、“22A”、“180-186”和“1-7A”应该都匹配,但是除了结尾之外的任何地方都应该匹配,任何带有多个连字符、字母或任何空格的东西也不应该匹配。

I'd also accept any answer that suggests a reasonable compromise to my strict definition of a house or building number.我也接受任何对我对房屋或建筑编号的严格定义提出合理妥协的答案。

Any help would be very much appreciated:-)任何帮助将不胜感激:-)

It turns out that VS Code had simply turned my hyphen into an em dash when I was typing static values into the HTML...d'oh!事实证明,当我在 HTML 中键入 static 值时,VS Code 只是将我的连字符变成了一个破折号……d'oh!

Anyway thanks to everyone who commented for trying to help:-)无论如何,感谢所有评论试图提供帮助的人:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM