ChatGPT解决这个技术问题 Extra ChatGPT

HTML5 form required attribute. Set custom validation message?

I've got the following HTML5 form: http://jsfiddle.net/nfgfP/


Remember me:

Currently when I hit enter when they're both blank, a popup box appears saying "Please fill out this field". How would I change that default message to "This field cannot be left blank"?

EDIT: Also note that the type password field's error message is simply *****. To recreate this give the username a value and hit submit.

EDIT: I'm using Chrome 10 for testing. Please do the same

Oh, +1 for the insane empty-password validation message =/ How did that pass QA, I wonder...
Why not just accept the browser default message? That's what users see for every other site they visit, you'll just confuse your users by creating a non-standard message. (Google has probably managed more UX evaluation & testing in determining that wording than you have!).
@ChrisV What about multilanguage sites?
In my case I want to check that the value is a number before posting but I can't use the type="number" attribute (for reasons.) So I set the pattern attribute to check for numbers and optional decimals which gives the message, "Please match the requested format," on error. I'd rather it said, "Ye must gift us a number bucko."

P
Philippe Fanaro

Here is the code to handle custom error message in HTML5:

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

This part is important because it hides the error message when the user inputs new data:

oninput="this.setCustomValidity('')"

Works perfectly on Firefox 29.0 and Chrome 34.0.1847.137.
perfect and in FF 38 so far. Fixes bug in email validation if only oninvalid() is used.
@somnath-kadam Is it a mistake or you intentionally did oninput="setCustomValidity('')" instead of oninput="this.setCustomValidity('')"
Thanks for marking oninput="setCustomValidity('')" as most important. This saved my day.
Note that you can even omit the this. in this case because inline event handlers run with a with(this) (not saying you should)
C
Community

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

I changed to vanilla JavaScript from Mootools as suggested by @itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.

Edit

I've updated the code here as setCustomValidity works slightly differently to what I understood when I originally answered. If setCustomValidity is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.

Further edit

As pointed out in @thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid otherwise there may be an extra pass through the oninvalid handler to clear it.


I tried this but there is still an error. If you leave the field empty it shows the message, then enter something in the field but it now shows an empty message and the action isn't executed. If you now click the button again, it will go through.
@thomasvdb Try setting custom validity to an empty string on the input event. At the moment it's only getting cleared if the invalid event gets fired.
This is indeed the solution. Found it out with the solution of @hleinone. Thanks for the response!
The solution above only uses JQuery to wait for the document to load. Everything else is pure JS and DOM. A browser modern enough to support setCustomValidity should also support the DOMContentLoaded event, meaning JQuery is not needed, if it is not used for anything else.
@Lai32290 because you are not accessing the actual DOM object. $("") returns an array of objects, even if there is only one. $("")[i] is most likely what you want.
A
Ashwini Jain

It's very simple to control custom messages with the help of HTML5 event oninvalid

Here is code:

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

This is most important:

onvalid="this.setCustomValidity('')"

Also check other validations as well such as pattern, min/max values, etc... sanalksankar.blogspot.com/2010/12/…
This causes a bug in firefox where it validates upon refresh, yet fails upon change and correction.
@RyanCharmley by using onchange="this.setCustomValidity('')" the bug will be gone. Check my answer below.
If this does not work (it does not in Safari, for example), use oninput instead of onvalid.
@Jimothy is right about this, oninput is the more universal solution, onvalid did not work even in Chrome for me.
k
kzh

Note: This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.

If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)

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

See http://jsfiddle.net/kaleb/nfgfP/8/

And in Firefox, you can add this attribute:

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

Edit

This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.

Edit 2

Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.


This doesn't change the actual message content.
At the time I testing it did.
My mistake, OP specified Chrome 10, I was on FF5. Removed downvote, my apologies. Wow, that error message in Chrome is the ugliest thing I've ever seen.
For declarative error messages in Firefox use the attribute: x-moz-errormessage="This field should not be left blank."
This adds a descriptive message under the "Please fill out this field".
G
George G

It's very simple to control custom messages with the help of the HTML5 oninvalid event

Here is the code:

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

it is required to set validity message to blank once control reveives input else first executed validity message will be displayed for all fields. Add oninput="setCustomValidity('')" whenever calling setCustomValidity(). +1 to Somnath's answer.
S
Salar

By setting and unsetting the setCustomValidity in the right time, the validation message will work flawlessly.

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

I used onchange instead of oninput which is more general and occurs when the value is changed in any condition even through JavaScript.


This should be the accepted answer. Worked in Windows 10 1709 in the following browsers: Chrome 66.0.3359.139 64 bits, Firefox 59.0.3 (64-bit), Internet Explorer 11.431.16299.0, Edge 41.16299.402.0. Worked in macOS 10.13.2 in Safari 11.0 (13604.1.38.1.6). Worked in Android 4.4.4 in Chrome 66.0.3359.158. For those looking for the JSX way: onInvalid={(e) => { e.target.setCustomValidity('foo') }} onChange={(e) => { e.target.setCustomValidity('') }}.
Addendum: e might be null, for example when an option is removed from a React Select field. Don't forget to check for that.
Errata: to use this with React Select, you have to pass onChange and onInvalid as inputProps={{ onInvalid: …, onChange: …, }}
Addendum: type='email' is a bit more difficult to treat, since using setCustomValidity sets customError: true to e.target.validity even if the input is valid. I'm trying to find a way to fix it.
@EvilJordan Email here
h
hleinone

I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title in Chrome or x-moz-errormessage in Firefox. Go check it out on GitHub, and give feedback.

It's used like:

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

There's a demo available at jsFiddle.


Thanks! Solved my little bug mentioned as a comment in the accepted answer.
Good answe, since OP is using Google Chrome; thoug this won't work in IE Edge
A
Ashish Marwal

Try this one, its better and tested:

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/


hey....nice solution but type=email doesnot work in safari browser . have a look w3schools.com/html/html_form_input_types.asp
Yes, it is not supported for safari, but I gave an answer for set custom validation message.
C
Collin White

https://i.stack.imgur.com/NeZ6B.png

le javascript

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

and some super HTML5

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

Despite the error saying only letters, the pattern allows space and apostrophe? Also, A-z allows '[', '\', ']', '^', '_', and '`'.
A
Andrei Veshtard

The solution for preventing Google Chrome error messages on input each symbol:

Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.




On first look, I thought I knew why this works, but I can't figure it out. Could somebody explain? (how does the IIFE change this?)
b
bernhardh

I have a simpler vanilla js only solution:

For checkboxes:

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

For inputs:

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

U
Umesh Patil

Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,

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


G
GuiRitter

Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.

I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:

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

C
Carson

If your error message is a single one, then try below.

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

To handle multiple errors, try below

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

Example

You can test valueMissing and valueMissing.

ValidityState


A
Ajay
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('');
    }

})


B
Baro

For a totaly custom check logic:

$(document).ready(function() { $('#form').on('submit', function(e) { if ($('#customCheck').val() != 'apple') { $('#customCheck')[0].setCustomValidity('Custom error here! "apple" is the magic word'); $('#customCheck')[0].reportValidity(); e.preventDefault(); } }); $('#customCheck').on('input', function() { $('#customCheck')[0].setCustomValidity(''); }); }); input { display: block; margin-top: 15px; } input[type="text"] { min-width: 250px; }


D
Deepti

Can be easily handled by just putting 'title' with the field:

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

This doesn't change the error message displayed. It only shows a title on the input when you hover.
This is not the correct usability of "title" to show some alert for the input field.
'title' doesn't change the default 'required' message.
Title has a very different purpose altogether.