更改默认的HTML输入验证消息 [英] Change default HTML input validation message

查看:56
本文介绍了更改默认的HTML输入验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过例如覆盖错误消息Firefox for HTML5表单,带有我自己的个人消息.但是这样做会导致我将其应用于输入字段,从而不允许表单提交.好像您没有填写输入字段,而是继续出现错误消息.

HTML部分

I want to override the error messages by e.g. Firefox for my HTML5 form with my own personal message. But doing this causes the input field I am applying it to to not allow the form to submit. It's as if you haven't filled in the input field and the error message keeps appearing instead.

HTML part

<label for="name">Name</label>
<input id="name" name="name" placeholder="Enter Your Name" required="" type="text">

JavaScript(IIFE)

Javascript (IIFE)

var change_text = function(){
var name = document.getElementById("name");
   if (!name.checkValidity())  {
        name.setCustomValidity("Please enter your full name"); 
        name.reportValidity();
  } 
    else {
        name.setCustomValidity("");
    }
  }();

这确实将邮件更改为我的定制邮件,但不允许表单提交.有趣的是,如果我将消息更改为空字符串,则可以正常工作(但显然不会显示错误消息.

This does change the message to my bespoke message, but it won't allow the form to submit. Interestingly, if i change my message to an empty sting, it does work (but obviously the error message doesn't show.

推荐答案

您可以使用 input invalid 事件来设置您的自定义验证消息.

You can use the input and invalid events to set your custom validation message.

let name = document.getElementById("name");
name.addEventListener("input", function(e){
  name.setCustomValidity('');//remove message when new text is input
});
name.addEventListener("invalid", function(e){
  name.setCustomValidity('Please enter your full name');//custom validation message for invalid text
});

<form>
  <label for="name">Name</label>
  <input id="name" name="name" placeholder="Enter Your Name" type="text" required autocomplete="off">
</form>

这篇关于更改默认的HTML输入验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆