简体   繁体   中英

Match input field with pattern

Im using a java script method to check if fields are valid so that the form can continue. This works fine until it gets to the post code because that has to be a specific pattern .

Is there anyway to check if the value of the field matches the pattern and then allow the form to continue.

As you can see , its set to only let the form progress if the lengths are greater than 0 , which is not good for the form , but worse for the postcode part.

Javascript:

function processPhase2(){
houseN = _("Hnumber").value;
lineone = _("Caddress1").value;
linetwo = _("Caddress2").value;
cityC = _("Ccity").value;
countyC = _("Ccounty").value;
postalcodeC = _("Cpostalcode").value;
if(houseN.length > 0 && lineone.length > 0 && cityC.length > 0 && countyC.length > 0 && postalcodeC.length > 0){
    _("phase2").style.display = "none";
    _("phase3").style.display = "block";
    _("progressBar").value = 66;
    _("status").innerHTML = "Phase 3 of 3";
} else {

}

}

Input field:

    <label for="postalcode">Postal Code</label>
<input type="text" name="Cpostalcode" id="Cpostalcode" size="20" required pattern="[A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]? [0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}" placeholder="eg: W1C 8LT" title="Must match pattern">

Grab the pattern with getAttribute and apply it to a new RegExp(pattern) . Then, you can just use the RegExp test method.

var elem = document.getElementById("Cpostalcode");

var pattern = elem.getAttribute("pattern");
var re = new RegExp(pattern);
if (re.test(elem.value)) {
    // Pattern matches!
} else {
    // Pattern does NOT match.
}

JSFiddle


Note: You should add the start ( ^ ) and end ( $ ) characters to your pattern or else it will test for substrings rather test than the entire string. You could do this with var re = new RegExp("^"+pattern+"$") or in the pattern attribute itself. ( More on that... )

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