Javascript 简明教程

JavaScript - Forms API

Web Forms API

JavaScript Forms API 是一种 Web API,允许我们与 HTML 表单进行交互并操控它们。它提供了一组用于执行客户端表单验证的方法和属性。它还有助于在提交表单之前确保数据的完整性。Forms API 也被称为表单验证 API 或约束验证 API。

JavaScript Forms API is a web API that allows us to interact with and manipulate HTML forms. It provides a set of methods and properties that are used to perform client-side form validation. It’s also helpful to ensure data integrity before form submission. The forms API also referred to as Form Validation API or Constraint Validation API.

在这里,我们将讨论如何使用各种方法和属性来使用 JavaScript 验证表单数据。

Here, we will discuss how to use various methods and properties to validate the form data using JavaScript.

Constraint Validation DOM Methods

在 JavaScript 中,约束验证 DOM 方法通过引用输入字段来验证输入值。它根据你与输入一起使用的 HTML 属性验证输入值。

In JavaScript, the constraint validation DOM method validates the input value by referencing the input fields. It validates the input value based on the HTML attributes you have used with the input.

验证输入值后,它返回布尔值,表示输入值是否有效。

After validating the input value, it returns a boolean value, representing whether the input value is valid.

以下是约束验证方法的列表。

Here is the list of the constraint validation methods.

Method

Description

checkValidity()

It returns a boolean value based on whether the input element contains a valid value.

setCustomValidity()

It is used to set the custom message to the validationMessage property.

Syntax

我们可以遵循以下语法来使用表单验证方法。

We can follow the syntax below to use the form validation methods.

element.checkValidity()
OR
element.setCustomValidity(message);

在上述语法中,你需要使用选择器访问元素,并将其作为 checkValidity() 或 setCustomValidity() 方法的引用。setCustomValidity() 方法将字符串消息作为参数。

In the above syntax, you need to access the element using the selector and take it as a reference of the checkValidity() or setCustomValidity() method. The setCustomValidity() method takes the string message as an argument.

Example: Using the checkValidity() method

我们在下面的代码中创建了数字输入并将 10 设置为 min 属性。

We created the number input in the code below and set 10 to the min attribute.

在 validateInput() 函数中,我们使用 id 访问数字输入并使用 checkValidity() 验证数字输入的值。

In the validateInput() function, we access the number input using the id and use the checkValidity() to validate the value of the number input.

如果 checkValidity() 方法返回假,我们打印验证消息。否则,我们打印数字值。

If checkValidity() method returns false, we print the validation message. Otherwise, we print the numeric value.

<html>
<body>
   <input type = "number" min = "10" id = "num" required>
   <p id = "output"> </p>
   <button onclick = "validateInput()"> Validate Number </button>
   <script>
      const output = document.getElementById("output");
      function validateInput() {
         let num = document.getElementById("num");
         if (num.checkValidity() == false) {
            output.innerHTML = "Please enter a number greater than 10";
         } else {
            output.innerHTML = "Your number is " + num.value;
         }
      }
   </script>
</body>
</html>

Example: Using the setCustomValidity() Method

在下面的代码中,我们定义了数字输入以输入用户年龄。

In the below code, we have defined the number input to take the user’s age in the input.

在 validateAge() 函数中,我们使用其 id 访问年龄输入,并在输入值上执行自定义验证。根据验证,我们使用 setCustomValidity() 设置自定义验证消息。

In the validateAge() function, we access the age input using its id and perform the custom validation on the input value. Based on the validation, we use the setCustomValidity() to set the custom validation message.

最后,我们使用 reportValidity() 方法来显示使用 setCustomValidity() 方法设置的验证消息。

At last, we use the reportValidity() method to show the validation message set using the setCustomValidity() method.

你可以输入小于 18 岁的年龄,并观察验证消息。

You can enter the age below 18, and observe the validation message.

<html>
<body>
   <form>
      <label> Enter your age: </label>
      <input type = "number" id = "age" required> <br> <br>
      <button type = "button" onclick = "validateAge()"> Validate Age </button>
   </form>
   <div id = "message"> </div>
   <script>
      function validateAge() {
         const ageInp = document.getElementById("age");
         const output = document.getElementById("message");
         const age = parseInt(ageInp.value);
         if (isNaN(age)) {
            ageInp.setCustomValidity("Please enter a valid number.");
         } else if (age < 18) {
            ageInp.setCustomValidity("You must be at least 18 years old.");
         } else {
            ageInp.setCustomValidity(""); // To remove custom error message
            output.innerHTML = "Age is valid!";
         }

         ageInp.reportValidity(); // To display custom validation message
      }
   </script>
</body>
</html>

Constraint Validation DOM Properties

JavaScript 还包含约束验证的 DOM 属性。它用于检查输入值的特定验证。

JavaScript also contains the DOM properties for constraint validation. It is used to check the particular validation of the input value.

在此,我们列出了可用于约束验证的所有 DOM 属性。

Here, we have listed all DOM properties that can be used for the constraint validation.

Property

Description

validity

It contains multiple properties to perform the particular validation on the input element.

validationMessage

It contains the validation message when the input element doesn’t contain valid data.

willValidate

It represents whether the input data will be validated.

Properties of the 'validity' Property

在 JavaScript 中,每个元素都有包含多个属性的“有效性”属性。您可以使用“验证”属性的特定属性来执行验证。

In JavaScript, each element has the 'validity' property, containing multiple properties. You can use the particular property of the 'validation' property to perform the validation.

在此,我们列出了“有效性”属性的所有属性。

Here, we have listed all properties of the 'validity' property.

Property

Description

customError

It contains a true boolean value when you set the custom validity message.

patternMismatch

When the parent element’s value doesn’t match the pattern, it sets true.

rangeOverflow

It returns a boolean value based on whether the input value is greater than the max attribute’s value.

rangeUnderflow

It returns a boolean value based on whether the input value is less than the min attribute’s value.

stepMismatch

It returns a boolean value based on whether the step is mismatching in the numeric input.

tooLong

If the length of the input element’s value is greater than the maxLength attribute’s value, it returns true. Otherwise, it returns false.

typeMismatch

When the type of entered value doesn’t match the 'type' attribute’s value, it returns true.

valueMissing

It returns a boolean value based on whether the input element is empty.

valid

It returns true when the input element is valid.

Syntax

用户可以按照以下语法使用验证属性的属性。

Users can follow the syntax below to use the properties of the validation property.

element.validity.property;

您可以使用元素有效性属性的不同属性来验证输入元素的值。

You can use the different properties of the validity property of the element to validate the input element’s value.

Example

在下面的代码中,我们定义数字输入,并将“max”属性的值设置为 300。

In the below code, we have defined the number input and set 300 for the value of the ‘max’ attribute.

在 validateNumber() 函数中,我们使用 input 元素“validity”属性的“rangeOverflow”属性来检查输入值是否大于 300。

In the validateNumber() function, we use the ‘rangeOverflow’ property of the ‘validity’ property of the input element to check whether the input value is greater than 300.

如果范围溢出属性返回 true,则我们打印“数字太大”。否则,我们打印数字值。

If the rangeOverflow property returns true, we print the ‘Number is too large’. Otherwise, we print the numeric value.

<html>
<body>
   <form>
      <label> Enter Any Number: </label>
      <input type = "number" id = "num" max = "300" required> <br> <br>
      <button type = "button" onclick = "validateNumber()"> Validate Number </button>
   </form>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      function validateNumber() {
         const numInput = document.getElementById('num');
         if (numInput.validity.rangeOverflow) {
            output.innerHTML = "Number is too large";
         } else {
            output.innerHTML = "Number is valid";
         }
      }
   </script>
  </body>
</html>

Example

在以下代码中,我们定义了文本输入。

In the below code, we have defined the text input.

在 validateText() 函数中,我们访问字符串输入。然后,我们使用有效性属性的“valueMissing”属性来检查输入值是否为空。

In the validateText() function, we access the string input. After that, we used the ‘valueMissing’ property of the validity property to check whether the input value is empty.

在输出中,你可以让输入值保持为空,点击验证文本按钮并观察错误信息。

In the output, you can keep the input value empty, click the validate text button and observe the error message.

<html>
<body>
   <form>
      <label> Enter any text: </label>
      <input type = "text" id = "str" required> <br> <br>
      <button type = "button" onclick = "validateText()"> Validate Text </button>
   </form>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      function validateText() {
         const strInput = document.getElementById('str');
         if (strInput.validity.valueMissing) {
            output.innerHTML = "Please enter a value.";
         } else {
            output.innerHTML = "You have entered " + strInput.value + ".";
         }
      }
   </script>
</body>
</html>

你还可以使用“validity”属性的其他属性来验证表单输入数据。如果数据无效,你可以使用 setCustomValidity() 方法显示自定义错误信息。

You can also use the other properties of the ‘validity’ property to validate the form input data. If the data is not valid, you can show the custom error message using the setCustomValidity() method.