xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

HTML5 custom input form validate All In One

HTML5 custom input form validate All In One

HTML5 自定义输入表单验证

<form>
  <label for="ZIP">ZIP : </label>
  <input type="text" id="ZIP" />
  <label for="Country">Country : </label>
  <select id="Country">
    <option value="ch">Switzerland</option>
    <option value="fr">France</option>
    <option value="de">Germany</option>
    <option value="nl">The Netherlands</option>
  </select>
  <input type="submit" value="Validate" />
</form>

window.onload = () => {
  document.getElementById("Country").onchange = checkZIP;
  document.getElementById("ZIP").oninput = checkZIP;
}


function checkZIP() {
  // For each country, defines the pattern that the ZIP has to follow
  const constraints = {
    ch: [
             '^(CH-)?\\d{4}$', 
             "Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950"
    ],
    fr: [
             '^(F-)?\\d{5}$' , 
             "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012"
    ],
    de: [
             '^(D-)?\\d{5}$' ,
             "Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345"
    ],
    nl: [
             '^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$',
             "Netherland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS"
    ],
  };

  // Read the country id
  const country = document.getElementById("Country").value;

  // Get the NPA field
  const ZIPField = document.getElementById("ZIP");

  // Build the constraint checker
  const constraint = new RegExp(constraints[country][0], "");
  console.log(constraint);

  // Check it!
  if (constraint.test(ZIPField.value)) {
    // The ZIP follows the constraint, we use the ConstraintAPI to tell it
    ZIPField.setCustomValidity("");
  } else {
    // The ZIP doesn't follow the constraint, we use the ConstraintAPI to
    // give a message about the format required for this country
    ZIPField.setCustomValidity(constraints[country][1]);
  }
}

demo

refs

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Constraint_validation

https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-09-27 14:56  xgqfrms  阅读(24)  评论(0编辑  收藏  举报