6

Preface

once shared a pure CSS form verification function in the "Extreme Edition" without water, using pure CSS to achieve super sassy form verification function 160db4393b6335. Although relying only on CSS cannot meet our daily development needs, but with various native form verification API , the situation is different.

Let us find out below.

Related API

ValidityState

Each native form component will have an object used to describe the validation state of the element- ValidityState .

code show as below:

账号:<input data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required  id="input-text" />
<script>
  'use strict';
  const inputText = document.querySelector('#input-text');
  inputText.addEventListener('input', event => {
    console.table(inputText.validity);
  });
</script>

The output is as follows:

The specific attributes are as follows:

AttributesOptional valueDescription
valueMissing (read only)true / falseWhen the form element has the attribute required value is empty, it is true , otherwise it is false . This attribute is associated with the pseudo-class :valid / :invalid .
typeMismatch (read only)true / falseWhen the value of the type of the form input elements do not match true , otherwise false . This attribute is associated with the pseudo-class :valid / :invalid .
patternMismatch (read only)true / falseWhen the value of the input form elements pattern when the rule properties do not match true , otherwise false . This attribute is associated with the pseudo-class :valid / :invalid .
tooLong (read only)true / falseWhen the length of the input value of the form element exceeds the maxlength attribute, it is true , otherwise it is false . This attribute is associated with the pseudo-class :valid / :invalid .
tooShort (read only)true / falseWhen the length of the value entered in the form element is less than the minlength attribute, it is true , otherwise it is false . This attribute is associated with pseudo-classes :valid / :invalid and :in-range / :out-of-range .
rangeUnderflow (read only)true / falseWhen the value entered in the form element is less than the min attribute, it is true , otherwise it is false . This attribute is associated with pseudo-classes :valid / :invalid and :in-range / :out-of-range .
rangeOverflow (read only)true / falseWhen the input value of the form element is greater than the max attribute, it is true , otherwise it is false . This attribute is associated with pseudo-classes :valid / :invalid and :in-range / :out-of-range .
stepMismatch (read only)true / falseWhen the value of the input form element step time values do not match true , otherwise false . This attribute is associated with pseudo-classes :valid / :invalid and :in-range / :out-of-range .
badInput (read only)true / falseWhen the input value of the form element is incomplete and UA thinks that the current state of the form should not be submitted, it is true , otherwise it is false .
customError (read only)true / falseWhen the error information of the form element is setCustomValidity() method call, it is true , otherwise it is false .
valid (read only)true / falseWhen the form element is validated, it is true , otherwise it is false . This attribute is associated with the pseudo-class :valid / :invalid .

validationMessage

When the form element is validated correctly, it will return '' , otherwise it will return the default or error message set setCustomValidity()

The effect is as follows:

code show as below:

账号:<input data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required  id="input-text" />
<script>
    'use strict';
    const inputText = document.querySelector('#input-text');
    inputText.addEventListener('input', event => {
      console.table(inputText.validationMessage); // 验证错误时则返回 “请与所请求的格式保持一致。”
    });
</script>

willValidate

A read-only attribute, it returns true when the form element needs to be validated, otherwise it is false .

The effect is as follows:

code show as below:

账号:<input data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required  id="input-text" />
<script>
    'use strict';
    const inputText = document.querySelector('#input-text');
    inputText.addEventListener('input', event => {
      console.table(inputText.willValidate); // true
    });
</script>

setCustomValidity()

setCustomValidity() used to set the value of the validationMessage After setting setCustomValidity() , validity.customError will become true . If you need to reset, just enter an empty string.

Let's look at the renderings:

code show as below:

<form class="form" id="form" method="get" action="/api/form">
      账号:
    <input id="account" data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required />
    <input id="submit" name="button" type="submit" value="提交" />
</form>

<script>
    'use strict';
    account.setCustomValidity('自定义错误!');
    form.addEventListener('submit', event => {
          event.preventDefault();
    });
</script>

checkValidity()

checkValidity() used to check whether the value of the current form element or the entire form is validated, if it is, it is true , otherwise it is false .

The effect is as follows:

code show as below:

账号:<input data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required  id="input-text" />
<script>
    'use strict';
    const inputText = document.querySelector('#input-text');
    inputText.addEventListener('input', event => {
          console.table(inputText.checkValidity());
    });
</script>

reportValidity()

reportValidity() used to trigger and check whether the value of the form element is validated, if it is, it is true , otherwise it is false .

The effect is as follows:

code show as below:

账号:<input data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required  id="input-text" />
<script>
    'use strict';
    const inputText = document.querySelector('#input-text');
    console.log(inputText.reportValidity());
</script>

The above API compatibility is as follows:

Picture from: https://caniuse.com/constraint-validation

A simple form submission example

We look at the effect:

code show as below:

<style>
    .form > input {
          margin-bottom: 10px;
    }
</style>
<form class="form" id="form" method="get" action="/api/form">
    账号:
    <input id="account" data-message="请输入正确的账号" data-title="账号" placeholder="请输入正确的账号" pattern="\w{6,10}" name="account" type="text" required />
    <br />
    密码:
    <input id="password" data-message="请输入正确的密码" data-title="密码" placeholder="请输入正确的密码" pattern="\w{6,10}" name="password" type="password" required />
    <br />
    <input id="submit" name="button" type="submit" value="提交" />
</form>
<script>
  'use strict';
  const inputs = [account, password];
  inputs.forEach(input => {
      input.addEventListener('input', () => {
          input.setCustomValidity('');
          input.checkValidity();
      });
      input.addEventListener('invalid', event => {
          const { message } = event.target.dataset;
          const { validity: { valid } } = input;
          input.setCustomValidity('');
          if (!valid) {
                input.setCustomValidity(message);
          };
      });
  });
</script>

The above example can be viewed on the Codepen : https://codepen.io/krischan77/pen/RwGLaxa .

fish head Note: Mmmmm, the function is quite good, if it is not the native component style is too ugly, the performance of different browsers is inconsistent, and the style can not be modified, I think there should be many people who use native API development. . . I don't understand why W3C doesn't expose the attributes of style modification. . .

Reference

  1. "Extreme Edition" does not contain water, uses pure CSS to achieve super-
  2. "True Fragrance Warning" These 33 super useful CSS selectors, you may not have seen them before.
  3. form-control-infrastructure
  4. ValidityState
  5. HTMLFormElement
  6. Constraint validation API

陈大鱼头
962 声望3.1k 粉丝

Kris不只是一只鱼头