如何为HTML验证提供自定义验证错误消息?

时间:2018-12-21 08:48:18

标签: javascript jquery html css validation

当我使用默认的HTML验证时,它会显示默认的错误消息,而我不想显示给我的客户。我需要自定义消息,并为每个验证(例如最小值,最大值,类型和要求)提供不同的消息。例如:

  

该字段为必填项,该值不匹配

请参考传统的HTML代码:

<input type="text" required>

我想要这样的东西:

<input type="text" validation="required|my_message,min:5|my_message">

3 个答案:

答案 0 :(得分:1)

使用jQuery中的自定义库是完全有可能的,我建议-https://github.com/aslamanver/abvalidate

自定义消息-jQuery表单验证-abValidate.js

ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"

通过添加这些CDN使用此库

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">

初始化库

$(document).ready(function () {
    //.ab-form is your form class
    $(".ab-form").abValidate();
});

开始,现在您可以使用jQuery abValidate库使用自定义验证

<form class="ab-form" action="your_action_url">

   <!-- Input and error message should be in a div class -->
   <div class="my-form-group">
        <input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
        <div class="error"></div>
    </div><br>

    <div class="my-form-group">
        <input type="submit" name="submit" value="Submit">
    </div>

</form>

答案 1 :(得分:0)

尝试一下,它经过更好的测试: HTML:

<form id="myform">
<input id="email" 
       oninvalid="InvalidMsg(this);" 
       oninput="InvalidMsg(this);"
       name="email"  
       type="email" 
       required="required" />
<input type="submit" />

JAVASCRIPT:

function InvalidMsg(textbox) {
if (textbox.value === '') {
    textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
    textbox.setCustomValidity('please enter a valid email address');
} else {
   textbox.setCustomValidity('');
}

return true;

}

演示:

http://jsfiddle.net/patelriki13/Sqq8e/

答案 2 :(得分:0)

您可以使用setCustomValidity

document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("This field cannot be left blank");
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})