📌  相关文章
📜  在 HTML5 中带有自定义验证消息的表单必需属性

📅  最后修改于: 2022-05-13 01:58:09.965000             🧑  作者: Mango

在 HTML5 中带有自定义验证消息的表单必需属性

Web 表单的创建一直是一项奇特的任务。虽然标记形状本身很简单,但检查每个字段是否具有有效且连贯的价格却更加困难,并且将此事告知用户可能会令人头疼。 HTML5 引入了新的表单机制。有两种约束验证 DOM 方法,它们是 checkValidity() 和 setCustomValidity()。让我们更多地了解它们。

checkValidity() 方法

我们首先使用 checkValidity() 方法检查输入字段是否包含有效数据,并在表单提交时运行 checkValidity() 以验证所有表单字段。如果至少有一个无效,则验证失败。通过使用 checkValidity() 方法,我们在 blur 事件上验证每个 input 元素或在 change 事件上验证每个 select 元素。这允许用户知道所选字段在给定时间是有效还是无效,并可以及时传达用户反馈。

句法:

input="this.checkValidity()"

如果输入元素包含有效数据,这将返回 true。

示例:此示例显示如何执行 HTML 表单所需属性以及设置自定义验证消息。


  

  

    Form required Attribute | With message validation

  

  
    
  
        

GeeksforGeeks

           

Enter a number and click the button:

                                   

An message will display of ERROR, if the number            is lesser than 101 or greater than 999

        

                      
    输出:
  • 当我们加载代码时:
    ngcut
  • 当我们将该字段留空并单击按钮时:
    ngcut
  • 当您输入无效值时:
    ngcut
  • 当您输入有效值时:
    ngcut

设置自定义有效性()

在输入元素中,它用于设置validationMessage 属性。在 HTML5 表单中控制自定义验证消息确实非常容易。让我们来看看如何。

句法:

input="this.setCustomValidity()"

这部分至关重要,因为它会在用户输入新数据时隐藏错误消息。

示例:此示例显示如何执行 HTML 表单所需属性以及设置自定义验证消息。


  

  

    Form required Attribute | With custom message validation
    

  

    
           

GeeksforGeeks

           
            

Enter an Email Id:

                                  
    
             
    输出:
  • 当我们加载代码时:
    ngcut
  • 当我们将该字段留空并单击按钮时:
    ngcut
  • 当您输入无效的电子邮件 ID 时:
    ngcut
    三种类型的约束验证 DOM 属性:
  • validationMessage :当有效性为假时,它包含浏览器将显示的消息。
  • willValidate:它将指示何时验证输入元素。
  • 有效性:与输入元素的有效性相关,它将包含布尔属性。

    关于数据的有效性,还有九种有效性属性:

    PropertyDescription
    customErrorIf a custom validity message is set and it is set to true.
    patternMismatchIf an element’s value does not match its pattern attribute and it is set to true.
    rangeOverflowIf an element’s value is greater than it,s max attribute and it is set to true.
    rangeUnderflowIf an element’s value is less than its min attribute and it is set to true.
    stepMismatchIf an element’s value is invalid per its step attribute and it is set to true.
    tooLongIf an element’s value exceeds its maxLength attribute and it is set to true.
    typeMismatchIf an element’s value is invalid per its type attribute and it is set to true.
    validIf an element’s value is valid and it is set to true.
    valueMissingIf an element (with a required attribute) has no value and it is set to true.