Sample code for implementing form validation with pure CSS

Sample code for implementing form validation with pure CSS

In our daily business, form validation is a very common design requirement. Some login and registration boxes and questionnaires also require form validation.

Generally, our implementation idea is that JS monitors the input content of the input box, determines the user input content, and thus determines the next operation.

For example: (The following example comes from the excellent open source UI library, element)

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
  <el-form-item
    label="Age"
    prop="age"
    :rules="[
      {required: true, message: 'Age cannot be empty'},
      { type: 'number', message: 'Age must be a numeric value'}
    ]"
  >
    <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button>
    <el-button @click="resetForm('numberValidateForm')">Reset</el-button>
  </el-form-item>
</el-form>
<script>
  export default {
    data() {
      return {
        numberValidateForm: {
          age: ''
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

The above is our regular expression verification, which is basically completed with JS. So can we implement it with CSS? The answer is yes. Here is the DEMO

Implementing form validation with CSS

The form validation above is completely implemented by CSS, and the core attribute is CSS Level 4 Validity . The idea is to use the properties of :valid and :invalid to judge value of <input> .

Here is the full code

/*
 * css
 */
 :root {
 	--error-color: red;
 }
 .form > input {
 	margin-bottom: 10px;
 }
 .form > .f-tips {
 	color: var(--error-color);
 	display: none;
 }
 input[type="text"]:invalid ~ input[type="submit"],
 input[type="password"]:invalid ~ input[type="submit"] {
 	display: none;
 }
 input[required]:invalid + span {
 	display: inline;
 }
 
 /*
  *html
  */
<form class="form" id="form" method="get" action="/api/form">
    account:
    <input data-title="Account" pattern="[\w]{6,10}" name="account" type="text" required />
    <span class="f-tips">Please enter the correct account number</span>
    <br />
    password:
    <input data-title="Password" pattern="[\w]{6,10}" name="password" type="password" required />
    <span class="f-tips">Please enter the correct password</span>
    <br />
    <input name="button" type="submit" value="Submit" />
</form>

Effect screenshots

Knowledge points used

1. New attributes of <input> in HTML5 : pattern

MDN's explanation:

Regular expression to check the value of the control. The pattern must match the entire value, not just some subset. Use the title attribute to describe the mode to help users. This attribute applies when the value of the type attribute is text, search, tel, url, or email; otherwise it is ignored. (Compatible with IE10+)

Remark:

If the validation rules in pattern are illegal, for example, there are too many spaces in the length check, an error will be reported in the console. The details are as follows:

<input data-title="Account" pattern="/[\w]{6, 10}/" name="account" type="text" required />

The validation rules in CSS and JS are different. The following writing will be invalid. The core validation rules need to be wrapped in [] . (Currently, this is the case for several examples tested. The specific details still need to be checked in the data. If anyone knows more specific information, please let me know. Thank you!)

<input data-title="Account" pattern="/\w{6,10}/" name="account" type="text" required />

2. New properties of CSS Level 4 選擇器: invalid

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

<<:  Front-end JavaScript housekeeper package.json

>>:  Docker View the Mount Directory Operation of the Container

Recommend

Implementation of MySQL Shell import_table data import

Table of contents 1. Introduction to import_table...

Explain TypeScript enumeration types in detail

Table of contents 1. Digital Enumeration 2. Strin...

Linux uses shell scripts to regularly delete historical log files

1. Tools directory file structure [root@www tools...

CSS3 uses transform to create a moving 2D clock

Now that we have finished the transform course, l...

Understand CSS3 FlexBox elastic layout in 10 minutes

Basic Introduction Features Flexbox is a CSS disp...

HTML+CSS+jQuery imitates the search hot list tab effect with screenshots

Copy code The code is as follows: <!DOCTYPE ht...

Solve the problem of garbled data in MySQL database migration

Under the instructions of my leader, I took over ...

JavaScript built-in date and time formatting time example code

1. Basic knowledge (methods of date objects) 😜 ge...

How to regularly clean up docker private server images

Using CI to build docker images for release has g...

How to configure the same domain name for the front and back ends of nginx

This article mainly introduces the method of conf...

How to make a website front end elegant and attractive to users

The temperament of a web front-end website is a fe...

Two methods to implement Mysql remote connection configuration

Two methods to implement Mysql remote connection ...

Detailed explanation of Javascript Echarts air quality map effect

We need to first combine the air quality data wit...

How to solve the DOS window garbled problem in MySQL

The garbled code problem is as follows: The reaso...