阻止在 form.reset() 上验证

Prevent validation on form.reset()

本文关键字:验证 reset form      更新时间:2023-09-26

我有以下html形式:

<body>
    <div>
        <form id="callBackForm" class="custom eight form" method="post" enctype="multipart/form-data" action="thank-you.php">
            <div class="callBackFormDivs"> 
                <div style="padding:0;" class="four mobile-one columns">
                    <label for="name" class="left inline">Name</label>
                </div>
                <div class="eight mobile-three columns">
                    <input class="left" id="name" name="name" required type="text" />
                </div>
            </div>
            <div class="callBackFormDivs">
                <div style="padding:0;" class="four mobile-one columns">
                    <label for="Age" class="left inline">Age</label>
                </div>
                <div class="eight mobile-three columns">
                    <input class="left" id="Age" name="Age" required type="text" />
                </div>
            </div>
            <div class="callBackFormDivs callBackFormButtonContainer">          
                <div>
                    <input type="submit" value="Submit" alt="Submit">
                    <button class="button" style="font-weight:normal; height:34px; float:right;" onClick="fnClearForm()">RESET</button>
                </div>                  
            </div>  
        </form>
    </div>
</body>

请注意,这些字段上设置了必需属性。如果用户尝试在不输入任何文本的情况下提交表单,此属性将向用户显示错误消息。

页面上有一个重置按钮,该按钮使用 form.reset() 函数清除字段,如下所示:

function fnClearForm()
{
    document.getElementById('callBackForm').reset();                    
}

问题是,当表单重置时,它会导致验证触发,并向用户显示错误消息。

我该如何防止这种情况?

我知道我可以编写一个自定义验证器,这将解决这个问题,但我认为最好找到一种方法来使这种验证正常工作。

我确实发现了一些相关的问题,但没有一个能解决问题。

使用 html 属性type创建重置按钮。

<button type="reset" value="Reset">Reset</button>

http://www.w3schools.com/tags/att_button_type.asp

小提琴:https://jsfiddle.net/2t2Lhnb8/