简体   繁体   中英

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:

<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:

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. 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.

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.

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!

Anyway thanks to everyone who commented for trying to help:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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