【问题标题】:HTML5 form required attribute. Set custom validation message?HTML5 表单必需属性。设置自定义验证消息?
【发布时间】:2021-03-30 02:13:56
【问题描述】:

我有以下 HTML5 表单:http://jsfiddle.net/nfgfP/

<form id="form" onsubmit="return(login())">
<input name="username" placeholder="Username" required />
<input name="pass"  type="password" placeholder="Password" required/>
<br/>Remember me: <input type="checkbox" name="remember" value="true" /><br/>
<input type="submit" name="submit" value="Log In"/>

目前,当我在它们都为空白时按 Enter 键时,会出现一个弹出框,上面写着“请填写此字段”。如何将默认消息更改为“此字段不能留空”?

编辑: 另请注意,类型密码字段的错误消息只是*****。要重新创建它,请给用户名一个值并点击提交。

编辑:我正在使用 Chrome 10 进行测试。请做同样的事情

【问题讨论】:

  • 哦,为疯狂的空密码验证消息 +1 =/ 那是如何通过 QA 的,我想知道...
  • 为什么不直接接受浏览器默认消息呢?这就是用户在他们访问的每个其他网站上看到的内容,您只会通过创建非标准消息来混淆您的用户。 (在确定该措辞方面,Google 管理的用户体验评估和测试可能比您拥有的多!)。
  • @ChrisV 多语言网站呢?
  • 在我的情况下,我想在发布之前检查该值是否为数字,但我不能使用 type="number" 属性(出于某种原因。)所以我设置了模式属性来检查数字和可选的小数,在错误时给出消息“请匹配请求的格式”。我宁愿它说,“你必须给我们一个数字 bucko。”

标签: javascript html forms validation


【解决方案1】:

这是处理 HTML5 中自定义错误消息的代码:

<input type="text" id="username" required placeholder="Enter Name"
  oninvalid="this.setCustomValidity('Enter User Name Here')"
  oninput="this.setCustomValidity('')"/>

这部分很重要,因为它在用户输入新数据时隐藏了错误消息:

oninput="this.setCustomValidity('')"

【讨论】:

  • 在 Firefox 29.0 和 Chrome 34.0.1847.137 上完美运行。
  • 完美,到目前为止在 FF 38 中。如果仅使用 oninvalid(),则修复电子邮件验证中的错误。
  • @somnath-kadam 是错误还是您故意使用 oninput="setCustomValidity('')" 而不是 oninput="this.setCustomValidity('')"
  • 感谢您将 oninput="setCustomValidity('')" 标记为最重要。这节省了我的时间。
  • 请注意,在这种情况下,您甚至可以省略 this.,因为内联事件处理程序 run with a with(this)(并不是说您应该这样做)
【解决方案2】:

使用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("");
        };
    }
})

changed to vanilla JavaScript 来自 Mootools,正如 cmets 中 @itpastorn 所建议的那样,但如果需要,您应该能够计算出等效的 Mootools。

编辑

我在这里更新了代码,因为setCustomValidity 的工作方式与我最初回答时的理解略有不同。如果setCustomValidity 设置为空字符串以外的任何内容,则会导致该字段被视为无效;所以你必须在测试有效性之前清除它,你不能只是设置它而忘记。

进一步编辑

正如下面@thomasvdb 的评论中所指出的,您需要在invalid 之外的某些事件中清除自定义有效性,否则可能需要额外通过oninvalid 处理程序来清除它。

【讨论】:

  • 我试过了,但还是有错误。如果您将该字段留空,它会显示消息,然后在该字段中输入一些内容,但现在会显示一条空消息并且不会执行该操作。如果您现在再次单击该按钮,它将通过。
  • @thomasvdb 尝试在input 事件上将自定义有效性设置为空字符串。目前它只有在invalid 事件被触发时才会被清除。
  • 这确实是解决方案。通过@hleinone 的解决方案找到了它。感谢您的回复!
  • 上面的解决方案只使用JQuery等待文档加载。其他一切都是纯 JS 和 DOM。一个足以支持 setCustomValidity 的现代浏览器也应该支持 DOMContentLoaded 事件,这意味着如果 JQuery 不用于其他任何事情,则不需要它。
  • @Lai32290 因为您没有访问实际的 DOM 对象。 $("") 返回一个对象数组,即使只有一个。 $("")[i] 很可能是您想要的。
【解决方案3】:

借助HTML5事件oninvalid控制自定义消息非常简单

代码如下:

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

这是最重要的:

onvalid="this.setCustomValidity('')"

【讨论】:

  • 还要检查其他验证,例如模式、最小/最大值等...sanalksankar.blogspot.com/2010/12/…
  • 这会导致 Firefox 中的一个错误,它在刷新时验证,但在更改和更正时失败。
  • @RyanCharmley 使用onchange="this.setCustomValidity('')" 会消失。在下面检查我的答案。
  • 如果这不起作用(例如在 Safari 中不起作用),请使用 oninput 而不是 onvalid
  • @Jimothy 对此是正确的,oninput 是更通用的解决方案,onvalid 甚至在我的 Chrome 中都不起作用。
【解决方案4】:

注意:这不再适用于 Chrome,未在其他浏览器中测试。请参阅下面的编辑。这个答案留在这里供历史参考。

如果您觉得验证字符串确实不应该通过代码设置,您可以将输入元素的标题属性设置为“此字段不能留空”。 (适用于 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."

编辑

自从我最初写这个答案以来,这似乎已经改变了。现在添加标题不会更改有效性消息,它只是在消息中添加一个附录。上面的小提琴仍然适用。

编辑 2

从 Chrome 51 开始,Chrome 现在对 title 属性没有任何作用。我不确定这是在哪个版本中更改的。

【讨论】:

  • 这不会改变实际的消息内容。
  • 在我测试它的时候。
  • 我的错误,OP指定了Chrome 10,我在FF5上。删除了downvote,我很抱歉。哇,Chrome 中的错误消息是我见过的最丑的
  • 对于 Firefox 中的声明性错误消息,请使用属性:x-moz-errormessage="This field should not be left blank."
  • 这会在“请填写此字段”下添加一条描述性消息。
【解决方案5】:

借助HTML5oninvalid事件控制自定义消息非常简单

代码如下:

User ID 
<input id="UserID"  type="text" required 
       oninvalid="this.setCustomValidity('User ID is a must')">

【讨论】:

  • 一旦控件接收到输入,必须将有效性消息设置为空白,否则将为所有字段显示第一次执行的有效性消息。在调用 setCustomValidity() 时添加 oninput="setCustomValidity('')"。 +1 对 Somnath 的回答。
【解决方案6】:

通过在正确的时间设置和取消设置setCustomValidity,验证消息将完美运行。

<input name="Username" required 
oninvalid="this.setCustomValidity('Username cannot be empty.')" 
onchange="this.setCustomValidity('')" type="text" />

我使用了onchange 而不是oninput,后者更通用,即使通过 JavaScript 在任何条件下更改值都会发生。

【讨论】:

  • 这应该是公认的答案。在以下浏览器中的 Windows 10 1709 中工作:Chrome 66.0.3359.139 64 位、Firefox 59.0.3(64 位)、Internet Explorer 11.431.16299.0、Edge 41.16299.402.0。在 Safari 11.0 (13604.1.38.1.6) 中的 macOS 10.13.2 中工作。在 Chrome 66.0.3359.158 中的 Android 4.4.4 中工作。对于那些寻找 JSX 方式的人:onInvalid={(e) =&gt; { e.target.setCustomValidity('foo') }} onChange={(e) =&gt; { e.target.setCustomValidity('') }}.
  • 附录:e 可能为空,例如从 React Select 字段中删除选项时。不要忘记检查。
  • 勘误表:要将其与 React Select 一起使用,您必须将 onChangeonInvalid 传递为 inputProps={{ onInvalid: …, onChange: …, }}
  • 附录:type='email' 有点难以处理,因为即使输入有效,使用 setCustomValidity 也会将 customError: true 设置为 e.target.validity。我正在努力寻找解决方法。
  • @EvilJordan 电子邮件here
【解决方案7】:

我制作了一个小型库来轻松更改和翻译错误消息。您甚至可以通过错误类型更改文本,目前在 Chrome 中使用 title 或在 Firefox 中使用 x-moz-errormessage 不可用。去check it out on GitHub,并提供反馈。

它的用法如下:

<input type="email" required data-errormessage-value-missing="Please input something">

有一个demo available at jsFiddle

【讨论】:

  • 谢谢!解决了我在接受的答案中作为评论提到的小错误。
  • 好回答,因为 OP 使用的是谷歌浏览器;虽然这在 IE Edge 中不起作用
【解决方案8】:

试试这个,它更好并且经过测试:

HTML:

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

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/

【讨论】:

【解决方案9】:

我发现的最简单和最干净的方法是使用数据属性来存储您的自定义错误。使用一些自定义 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>

【讨论】:

  • 尽管错误只说字母,但该模式允许空格和撇号?此外,A-z 允许使用 '['、'\'、']'、'^'、'_' 和 '`'。
【解决方案10】:

防止谷歌浏览器在输入每个符号时出现错误消息的解决方案:

<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>

【讨论】:

  • 乍一看,我以为我知道为什么会这样,但我想不通。有人可以解释一下吗? (IIFE 如何改变这一点?)
【解决方案11】:

我有一个更简单的纯 js 解决方案:

对于复选框:

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

对于输入:

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

【讨论】:

    【解决方案12】:

    好的,oninvalid 效果很好,但即使用户输入了有效数据,它也会显示错误。所以我用下面的方法来解决它,希望它也对你有用,

    oninvalid="this.setCustomValidity('Your custom message.')"onkeyup="setCustomValidity('')"

    【讨论】:

      【解决方案13】:

      根据 Salar 对 JSX 和 React 的回答,我注意到 React Select 在验证方面的行为与 &lt;input/&gt; 字段不同。显然,需要几种解决方法来仅显示自定义消息并防止其在不方便的时间显示。

      我提出了一个问题here,如果它有帮助的话。 Here 是一个带有工作示例的 CodeSandbox,其中最重要的代码在此处复制:

      你好.js

      import React, { Component } from "react";
      import SelectValid from "./SelectValid";
      
      export default class Hello extends Component {
        render() {
          return (
            <form>
              <SelectValid placeholder="this one is optional" />
              <SelectValid placeholder="this one is required" required />
              <input
                required
                defaultValue="foo"
                onChange={e => e.target.setCustomValidity("")}
                onInvalid={e => e.target.setCustomValidity("foo")}
              />
              <button>button</button>
            </form>
          );
        }
      }
      

      SelectValid.js

      import React, { Component } from "react";
      import Select from "react-select";
      import "react-select/dist/react-select.css";
      
      export default class SelectValid extends Component {
        render() {
          this.required = !this.props.required
            ? false
            : this.state && this.state.value ? false : true;
          let inputProps = undefined;
          let onInputChange = undefined;
          if (this.props.required) {
            inputProps = {
              onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
            };
            onInputChange = value => {
              this.selectComponent.input.input.setCustomValidity(
                value
                  ? ""
                  : this.required
                    ? "foo"
                    : this.selectComponent.props.value ? "" : "foo"
              );
              return value;
            };
          }
          return (
            <Select
              onChange={value => {
                this.required = !this.props.required ? false : value ? false : true;
                let state = this && this.state ? this.state : { value: null };
                state.value = value;
                this.setState(state);
                if (this.props.onChange) {
                  this.props.onChange();
                }
              }}
              value={this && this.state ? this.state.value : null}
              options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
              placeholder={this.props.placeholder}
              required={this.required}
              clearable
              searchable
              inputProps={inputProps}
              ref={input => (this.selectComponent = input)}
              onInputChange={onInputChange}
            />
          );
        }
      }
      

      【讨论】:

        【解决方案14】:

        如果您的错误消息是单一的,请在下面尝试。

        <input oninvalid="this.setCustomValidity('my error message')"
               oninput="this.setCustomValidity('')">  <!-- ? don't forget it. -->
        

        要处理多个错误,请尝试以下操作

        <input oninput="this.setCustomValidity('')">
        <script>
        inputElem.addEventListener("invalid", ()=>{
            if (inputElem.validity.patternMismatch) {
              return inputElem.setCustomValidity('my error message')
            }
            return inputElem.setCustomValidity('') // default message
        })
        </script>
        

        示例

        您可以测试 valueMissing 和 valueMissing。

        <form>
        <input pattern="[^\\/:\x22*?<>|]+"
               placeholder="input file name"       
               oninput="this.setCustomValidity('')"
               required
        >
          <input type="submit">
        </form>
        
        <script>
          const form = document.querySelector("form")
        
          const inputElem = document.querySelector(`input`)
        
          inputElem.addEventListener("invalid", ()=>{   
            if (inputElem.validity.patternMismatch) {
              return inputElem.setCustomValidity('Illegal Filename Characters \\/:\x22?<>|')
            }
            return inputElem.setCustomValidity('') // return default message according inputElem.validity.{badInput, customError, tooLong, valueMissing ...}
          })
        
          form.onsubmit = () => {
            return false
          }
        </script>

        【讨论】:

          【解决方案15】:

          只需在字段中加上“标题”即可轻松处理:

          <input type="text" id="username" required title="This field can not be empty"  />
          

          【讨论】:

          • 这不会更改显示的错误消息。它仅在您悬停时在输入上显示标题。
          • 这不是“标题”的正确可用性来显示输入字段的一些警报。
          • 'title' 不会更改默认的 'required' 消息。
          • 标题的目的完全不同。
          猜你喜欢
          • 2012-11-27
          • 1970-01-01
          • 1970-01-01
          • 2012-11-04
          • 1970-01-01
          • 1970-01-01
          • 2014-11-04
          相关资源
          最近更新 更多