简体   繁体   English

HTML表单中的自定义错误消息

[英]Custom Error Message in HTML Form

I'm trying to set a custom error message in an HTML5 form with the required attribute, however it doesn't appear to be working. 我正在尝试使用required属性以HTML5格式设置自定义错误消息,但是它似乎无法正常工作。

Code: 码:

<form role="form" method="post" action="contact-form.php">
    <input type="text" class="input-field" name="name" id="name" placeholder="Name" required />
    <input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
    <textarea name="message" class="textarea-field" id="message" placeholder="Message"></textarea>
    <input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />             
</form>
<script>
    var name = document.querySelector( "#name" );
    function setErrorMessage() {
        if ( name.validity.valueMissing ) {
            name.setCustomValidity( "Please enter your name" );
        }
    };
setErrorMessage();
name.addEventListener( "change", setErrorMessage );
 </script>

Fiddle: http://jsfiddle.net/e4eutova/1/ 小提琴: http : //jsfiddle.net/e4eutova/1/

I've looked round and I thought the syntax was correct, but it doesn't appear to be. 我环顾四周,我认为语法是正确的,但似乎并非如此。 Any help would be greatly appreciated! 任何帮助将不胜感激!

没关系-我发现并正在使用此解决方案: https : //github.com/javanto/civem.js

As far as I know and understand the problem, you aren't calling the function setErrorMessage() anywhere. 据我了解和理解的问题,您没有在任何地方调用函数setErrorMessage()。 You need to add onClick="setErrorMessage() in your submit button input description. 您需要在提交按钮输入描述中添加onClick="setErrorMessage()

Also, I would try changing the code to use document.getElementById("_your_object_id_"); 另外,我将尝试更改代码以使用document.getElementById("_your_object_id_"); instead. 代替。 Or getElementsByName(). 或getElementsByName()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM