Constraint API: using setCustomValidity for country & ZIP

This commit is contained in:
NetMan 2024-02-24 17:45:32 +01:00
parent 27117cd641
commit 84cb547df8
2 changed files with 17 additions and 9 deletions

View File

@ -12,10 +12,9 @@
<input name="email" id="email" type="email" required placeholder="Email (christopher@example.com)"> <input name="email" id="email" type="email" required placeholder="Email (christopher@example.com)">
<input name="country" id="country" type="text" list="countries-list" required placeholder="Country (United Kingdom)"> <input name="country" id="country" type="text" list="countries-list" required placeholder="Country (United Kingdom)">
<output id="country-info"></output>
<datalist id="countries-list"></datalist> <datalist id="countries-list"></datalist>
<input name="zip" id="zip" type="text" required placeholder="ZIP code (12-345)" pattern="\d{2}-\d{3}"> <input name="zip" id="zip" type="text" required placeholder="ZIP code (12-345)">
<input name="password" id="password" type="password" required placeholder="Password (Pa$Sw0rD)"> <input name="password" id="password" type="password" required placeholder="Password (Pa$Sw0rD)">
<div id="password-check"> <div id="password-check">

View File

@ -48,16 +48,25 @@ document.addEventListener("DOMContentLoaded", () => {
alert("Hold up, one or more fields are invalid! Try again"); alert("Hold up, one or more fields are invalid! Try again");
} }
}); });
countryInput.addEventListener("input", () => { countryInput.addEventListener("input", () => {
countryInput.setAttribute( const valid = countryInput.value.search(COUNTRY_REGEX) >= 0;
"input-valid", countryInput.setAttribute("input-valid", valid);
countryInput.value.search(COUNTRY_REGEX) >= 0, if (valid) {
); countryInput.setCustomValidity("");
} else {
countryInput.setCustomValidity("Invalid country");
}
}); });
countryInput.addEventListener("change", () => { zipInput.addEventListener("input", () => {
document.querySelector("#country-info").textContent = const valid = zipInput.value.search(/\d{2}-\d{3}/) >= 0;
countryInput.value.search(COUNTRY_REGEX) >= 0 ? "" : "Invalid country"; zipInput.setAttribute("input-valid", valid);
if (valid) {
zipInput.setCustomValidity("");
} else {
zipInput.setCustomValidity("ZIP Code format should be 12-345");
}
}); });
passwordInput.addEventListener("input", checkPasswordValidity); passwordInput.addEventListener("input", checkPasswordValidity);