• Author: Chen Da Yu Tou
  • Making: KRISACHAN

preface

Fishhead has shared a fancy CSS form validation feature in “Extreme Edition” without water and with pure CSS. CSS alone is not enough to meet our daily development needs, but with various native form validation apis, things are different.

Let’s take a look.

This API

ValidityState

Each native form component has a ValidityState object that describes the validation state of the element.

The code is as follows:

Account:<input data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" 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>
Copy the code

The output is as follows:

The specific attributes are as follows:

attribute An optional value instructions
ValueMissing (read only) true / false When the form element is setrequiredProperties, andvalueIs nulltrue, or forfalse. This property is associated with the pseudo class:valid / :invalid
TypeMismatch (read only) true / false Is true when the value entered for a form element does not match the typetrue, or forfalse. This property is associated with the pseudo class:valid / :invalid
PatternMismatch (read only) true / false When a form element is entered with a valuepatternIf the rules of the attribute do not matchtrue, or forfalse. This property is associated with the pseudo class:valid / :invalid
TooLong (read only) true / false When the value entered for a form element exceeds the lengthmaxlengthAttributes fortrue, or forfalse. This property is associated with the pseudo class:valid / :invalid
TooShort (read only) true / false When a form element enters a value of less lengthminlengthAttributes fortrue, or forfalse. This property is associated with the pseudo class:valid / :invalidAs well as:in-range / :out-of-range
RangeUnderflow (read Only) true / false When the value entered for a form element is less thanminAttributes fortrue, or forfalse. This property is associated with the pseudo class:valid / :invalidAs well as:in-range / :out-of-range
RangeOverflow (read only) true / false When the value entered for the form element is greater thanmaxAttributes fortrue, or forfalse. This property is associated with the pseudo class:valid / :invalidAs well as:in-range / :out-of-range
StepMismatch (read only) true / false When a form element is entered with a valuestepIs when the value oftrue, or forfalse. This property is associated with the pseudo class:valid / :invalidAs well as:in-range / :out-of-range
BadInput (read only) true / false When a form element enters incomplete values andUAWhen you think the form in its current state should not be submittedtrue, or forfalse.
CustomError (read only) true / false When a form element error message is sent bysetCustomValidity()Method calls are displayed astrue, or forfalse.
Valid (read only) true / false When the form element is validatedtrue, or forfalse. This property is associated with the pseudo class:valid / :invalid

validationMessage

Returns ” if the form element validates correctly, otherwise returns an error message set by default or via the setCustomValidity() method.

The effect is as follows:

The code is as follows:

Account:<input data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" 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); // In case of a validation error, "Please keep the format as requested."
    });
</script>
Copy the code

willValidate

A read-only property that returns true if a form element requires validation and false otherwise.

The effect is as follows:

The code is as follows:

Account:<input data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" 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>
Copy the code

setCustomValidity()

SetCustomValidity () sets the value of the form element validationMessage. Validity.customerror becomes true when setCustomValidity() is set. If you need to reset, enter an empty string.

Let’s take a look at the effect:

The code is as follows:

<form class="form" id="form" method="get" action="/api/form">Account:<input id="account" data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" name="account" type="text" required />
    <input id="submit" name="button" type="submit" value="Submit" />
</form>

<script>
    'use strict';
    account.setCustomValidity('Custom error! ');
    form.addEventListener('submit'.event= > {
      	event.preventDefault();
    });
</script>
Copy the code

checkValidity()

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

The effect is as follows:

The code is as follows:

Account:<input data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" 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>
Copy the code

reportValidity()

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

The effect is as follows:

The code is as follows:

Account:<input data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" name="account" type="text" required  id="input-text" />
<script>
    'use strict';
    const inputText = document.querySelector('#input-text');
    console.log(inputText.reportValidity());
</script>
Copy the code

The compatibility of the above apis is as follows:

Image from: caniuse.com/constraint-…

A simple form submission example

Let’s look at the effect:

The code is as follows:

<style>
    .form > input {
      	margin-bottom: 10px;
    }
</style>
<form class="form" id="form" method="get" action="/api/form">Account:<input id="account" data-message="Please enter the correct account number" data-title="Account" placeholder="Please enter the correct account number" pattern="6, 10 {} \ w" name="account" type="text" required />
    <br />Password:<input id="password" data-message="Please enter the correct password" data-title="Password" placeholder="Please enter the correct password" pattern="6, 10 {} \ w" name="password" type="password" required />
    <br />
    <input id="submit" name="button" type="submit" value="Submit" />
</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>
Copy the code

The above example can be found in Codepen: codepen. IO /krischan77/… On the view.

Note: Mmmmm, the functionality is fine, but if the native component style is not ugly, different browser performance is not consistent, and the style can not be changed, I think there will be a lot of people using native API development… Wonder why the W3C doesn’t expose style modification properties…

The resources

  1. The “Extreme version” does not mix water, using pure CSS to achieve super – sayable form verification function
  2. 33 super handy CSS selectors that you’ve probably never seen before.
  3. form-control-infrastructure
  4. ValidityState
  5. HTMLFormElement
  6. Constraint validation API