首页 文章

HTML5表单必需属性 . 设置自定义验证消息?

提问于
浏览
244

我有以下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/>

Remember me: <input type="checkbox" name="remember" value="true" />
<input type="submit" name="submit" value="Log In"/>

目前当我在空白时点击输入时,会出现一个弹出框,上面写着“请填写此字段” . 如何将该默认消息更改为“此字段不能留空”?

EDIT: 另请注意,类型密码字段的错误消息只是 ***** . 要重新创建此项,请为用户名提供值并点击提交 .

EDIT :我正在使用Chrome 10进行测试 . 请这样做

13 回答

  • 214

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

    这是代码:

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

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

    我是来自Mootools的changed to vanilla JavaScript,如评论中的@itpastorn所示,但是你应该能够在必要时计算出Mootools的等价物 .

    编辑

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

    进一步编辑

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

  • 0

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

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

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

    oninput="this.setCustomValidity('')"
    
  • 63

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

    这是代码:

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

    这是最重要的:

    onvalid="this.setCustomValidity('')"
    
  • 86

    Note: 此功能不再适用于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."
    

    编辑

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

    编辑2

    Chrome现在不对Chrome 51的title属性执行任何操作 . 我不确定此更改的版本 .

  • 0

    我创建了一个小型库来简化更改和翻译错误消息 . 您甚至可以使用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 .

  • 33

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

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

    我使用的是 onchange 而不是 oninput ,这更通用,即使通过JavaScript在任何条件下更改值也会发生 .

  • 31

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

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

    Demo:

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

  • 18

    这是非常简单的控制HTML输入类型所需的消息 . 不需要JS,或CSS只使用HTML5 .

    首先,您只能使用此“oninvalid”属性

    <input id="userid" type="text or others" required="" oninvalid="this.setCustomValidity('Hello Username cant be Blank!')">
    

    或者您可以使用“oninput”属性

    <input id="userid" type="text or others" required="" oninvalid="this.setCustomValidity('Hello Username cant be Blank!')" oninput="setCustomValidity('')">
    
  • 10

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

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

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

    对于复选框:

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

    输入:

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

    适应Salar 's answer to JSX and React, I noticed that React Select doesn' t的行为就像验证的 <input/> 字段一样 . 显然,需要一些变通方法来显示自定义消息并防止它在不方便的时候显示 .

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

    Hello.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}
          />
        );
      }
    }
    
  • 35

    好的,oninvalid运行良好但即使用户输入了有效数据也显示错误 . 所以我用下面的方法解决它,希望它对你也有用,

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

相关问题