This is the 30th day of my participation in the August Challenge

When we collect user input content, we definitely need to judge whether the user input content is what we need. There are many apis in JS that can assist us to constrain the user input correct content.

Required fields

The Required attribute is specifically set to determine whether the input, TextaREA, and SELECT elements are empty, and automatically prompt for the content if they are.

 <input type="text" value="" required>
Copy the code

Note that some browser versions may not support this property, here are the supported browser versions. I’ll put the query compatibility link here, which everyone on the front end must knowCan I use… Support tables for HTML5, CSS3, etc.

Input type restriction

The html5 specification adds email and url attributes to the input element, both of which are browser-provided custom validations.

  • Email Authentication Email
  • Url Browser address
        <input type="email" value="" > <br>
        <input type="url" value="" /><br>
        <button type="submit">submit</button>
Copy the code

There is also a browser version limit, you can use query compatibility to check.

Input value range

In addition to the above two attributes, there are:

“Number”, “range”, “datetime”, “datetime-local”, “date”, “month”, “week”, and “time”.

Not all major browsers support these types, so be careful when using them.

You can specify min, Max, and step. If you can only type in multiples of 0 to 100, you can write this

 <input type="number" max="100" min="0" step="3">

Copy the code

The input mode

Pattern property, which is used to specify a regular expression. The user input must match the re.

<input type="text" pattern="[0-9]." > // Set the value between 0 and 9, and only one digit

Copy the code

We wrote a very simple re: set the value between 0 and 9, and it is only one digit. You can see the graph, and it will tell you if we don’t agree with what we typed.

Check validity

The checkValidity() method can be used to check whether the content in the form is valid, returning true if valid and false if invalid.

<input type="text" value="11" pattern="[0-9]." >

let inputs = document.querySelectorAll('input');
console.log(inputs[0].checkValidity())
Copy the code

Disable validation

The novalidate property disables any validation on the form. If we have many forms, especially for loops, that do not require validation, we can disable the validation property.

It feels like development rarely needs this, it’s easy to inject into SQL, and it causes other hazards.

These are relatively new things, although not new, out for a long time. If we need to be compatible with older browsers in the project, we should try not to use these, which may cause compatibility problems.