我有以下HTML5形式:http://jsfiddle.net/nfgfP/

<form id=“onsubmit”=“return(登录)“> <输入=“用户名” <输入=“pass”类型=“密码” <br/> reminme: <输入类型=“checkbox” <输入类型=“submit”

目前,当我点击enter时,它们都是空白的,弹出框显示“请填写此字段”。如何将默认消息更改为“此字段不能留空”?

编辑:还要注意,类型密码字段的错误消息仅仅是*****。为了重新创建这个,给用户名一个值并点击submit。

编辑:我使用Chrome 10进行测试。请也这样做


当前回答

我有一个更简单的香草js唯一的解决方案:

复选框:

document.getElementById("id").oninvalid = function () {
    this.setCustomValidity(this.checked ? '' : 'My message');
};

输入:

document.getElementById("id").oninvalid = function () {
    this.setCustomValidity(this.value ? '' : 'My message');
};

其他回答

解决方案防止谷歌Chrome错误消息输入每个符号:

<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p> <form method="post" action="#"> <label for="text_number_1">Here you will see browser's error validation message on input:</label><br> <input id="test_number_1" type="number" min="0" required="true" oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('This is my custom message.')"/> <input type="submit"/> </form> <form method="post" action="#"> <p></p> <label for="text_number_1">Here you will see no error messages on input:</label><br> <input id="test_number_2" type="number" min="0" required="true" oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)" oninvalid="this.setCustomValidity('This is my custom message.')"/> <input type="submit"/> </form>

注意:这不再工作在Chrome,没有测试在其他浏览器。见下面的编辑。这个答案留作历史参考。

如果您觉得验证字符串真的不应该由代码设置,您可以将输入元素的title属性设置为“此字段不能留空”。(适用于Chrome 10)

title="This field should not be left blank."

参见http://jsfiddle.net/kaleb/nfgfP/8/

在Firefox中,你可以添加这个属性:

x-moz-errormessage="This field should not be left blank."

Edit

自从我最初写下这个答案以来,这似乎已经改变了。现在添加标题并不会改变有效性消息,它只是向消息添加了一个附录。上述说法仍然适用。

编辑2

Chrome现在不做任何与标题属性的Chrome 51。我不确定这在哪个版本中发生了变化。

我发现的最简单、最干净的方法是使用数据属性来存储自定义错误。测试节点的有效性,并使用一些自定义html处理错误。

le javascript

if(node.validity.patternMismatch)
        {
            message = node.dataset.patternError;
        }

以及一些超级HTML5

<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>

在HTML5 event oninvalid的帮助下控制自定义消息是非常简单的

下面是代码:

<input id="UserID"  type="text" required="required"
       oninvalid="this.setCustomValidity('Witinnovation')"
       onvalid="this.setCustomValidity('')">

这是最重要的:

onvalid="this.setCustomValidity('')"
const username= document.querySelector('#username');
const submit=document.querySelector('#submit');

submit.addEventListener('click',()=>{
    if(username.validity.typeMismatch){
        username.setCustomValidity('Please enter User Name');
    }else{
        username.setCustomValidity('');
    }
if(pass.validity.typeMismatch){
        pass.setCustomValidity('Please enter Password');
    }else{
        pass.setCustomValidity('');
    }

})