samedi 11 janvier 2020

Regex.test(value) returns true when logged but false within an if statement

I'm noticing something weird with my code. I have a regex to check UK postcodes, it uses capture groups and works fine unless within an if statement. The code to test is within a validator class which is passed an HTML node list with all fields from a form.

For example, when I use it within the pattern tag on the HTML input field it acts as you would expect. As it does when I console.log(regex.test(field.value)). However, when I put it into an if statement it seems to fail every time.

The regex is as follows:

/\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b/

The input field is as follows:

<input required pattern="\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b" inputmode="text" class="form-field" type="text" name="postcode" id="contactPostcode" placeholder="Postcode eg NW2 8BZ" />

The code to test it is as follows:

validate(fields)

// ... omitted ... //

let errors = [];

const postcodeRegex = /\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b/;

postcodeRegex.lastIndex = 0;

for (let field of fields) {

    if(field.name === 'postcode') {
        console.log(postcodeRegex.test(field.value))
        if(!postcodeRegex.test(field.value)) {
            errors.push({
                field: field.getAttribute('name'),
                error: 'Illegal character detected'
            });
            continue;
        }
    }

}

The console.log check returns true however the if statement check returns false every time and I don't understand why the two identical checks would output different results, does anyone have any advice? I am guessing something is going over my head here.

Thanks

Edit for clarification: The console log's true but the if statement is still being executed

Aucun commentaire:

Enregistrer un commentaire