Wymagany atrybut formularza HTML5. Ustawić niestandardowy komunikat walidacji?

Mam następujący formularz 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"/>

Obecnie, gdy nacisnę enter, gdy oba są puste, pojawia się okienko z napisem "Proszę wypełnij To pole". Jak zmienić domyślną wiadomość na "to pole nie może być puste"?

EDIT: należy również zauważyć, że komunikat o błędzie pola type password to po prostu *****. Aby to odtworzyć, podaj wartość nazwy użytkownika i naciśnij submit.

EDIT : Używam Chrome 10 do testowania. Proszę zrób to samo

Author: Damjan Pavlica, 2011-03-11

13 answers

Użycie 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 zmieniono na vanilla JavaScript z Mootools zgodnie z sugestią @itpastorn w komentarzach, ale powinieneś być w stanie wypracować odpowiednik Mootools, jeśli to konieczne.

Edytuj

Zaktualizowałem tutaj Kod, ponieważ setCustomValidity działa nieco inaczej niż to, co zrozumiałem, gdy odpowiedziałem. Jeśli setCustomValidity jest ustawione na coś innego niż pusty łańcuch, spowoduje to, że pole zostanie uznane za nieprawidłowe; dlatego musisz wyczyść go przed testowaniem ważności, nie możesz go po prostu ustawić i zapomnieć.

Dalsza edycja

Jak wspomniano w komentarzu @thomasvdb poniżej, musisz wyczyścić niestandardową ważność w niektórych przypadkach poza invalid, w przeciwnym razie może być dodatkowe przejście przez obsługę oninvalid, aby ją wyczyścić.

 211
Author: robertc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-18 02:09:28

Oto kod do obsługi niestandardowego komunikatu o błędzie w HTML5

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

Ta część jest ważna, ponieważ ukrywa komunikat o błędzie, gdy użytkownik wprowadza nowe dane:

    oninput="this.setCustomValidity('')"
 167
Author: Somnath Kadam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-10 12:02:49

Sterowanie niestandardowymi wiadomościami jest bardzo proste za pomocą zdarzenia HTML5 oninvalid

Oto kod:

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

To jest najważniejsze:

onvalid="this.setCustomValidity('')"
 85
Author: Ashwini Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 08:06:33

Uwaga: to nie działa już w Chrome, nie jest testowane w innych przeglądarkach. Zobacz zmiany poniżej. Ta odpowiedź jest pozostawiona tutaj dla odniesienia historycznego.

Jeśli uważasz, że łańcuch walidacji nie powinien być ustawiony za pomocą kodu, możesz ustawić atrybut title elementu wejściowego na "to pole nie może być puste". (Działa w Chrome 10)

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

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

A w Firefoksie możesz dodać to atrybut:

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

Edit

Wygląda na to, że zmieniło się to odkąd napisałem tę odpowiedź. Teraz dodanie tytułu nie zmienia ważności wiadomości, po prostu dodaje dodatek do wiadomości. Powyższe skrzypce nadal obowiązują.

Edycja 2

Chrome nie robi teraz nic z atrybutem title od Chrome 51. Nie jestem pewien, w której wersji to się zmieniło.

 62
Author: kzh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-16 10:57:14

Zrobiłem małą bibliotekę, aby ułatwić zmianę i tłumaczenie komunikatów o błędach. Możesz nawet zmienić teksty według typu błędu, który jest obecnie niedostępny za pomocą title w Chrome lub x-moz-errormessage w Firefox. Idź Sprawdź to na GitHub i podziel się swoją opinią.

Jest używany jak:

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

Istnieje demo dostępne w jsFiddle .

 34
Author: hleinone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-02 13:08:37

Bardzo łatwo jest kontrolować niestandardowe wiadomości za pomocą HTML5 oninvalid event

Oto kod:

User ID 
<input id="UserID"  type="text" required 
       oninvalid="this.setCustomValidity('User ID is a must')">
 33
Author: Dharmendra Jha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-13 20:10:33

Ustawiając i wyłączając setCustomValidity we właściwym czasie, komunikat walidacji będzie działał bezbłędnie.

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

Użyłem onchange zamiast oninput, co jest bardziej ogólne i występuje, gdy wartość jest zmieniana w dowolnym stanie, nawet przez JavaScript.

 30
Author: Salar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-29 06:14:18

Spróbuj tego, jest lepszy i przetestowany:

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/

 14
Author: Rikin Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-11 14:51:30

Jest to bardzo proste kontrolowanie wymaganej wiadomości typu wejścia HTML. Nie trzeba JS, lub CSS używać tylko HTML5.

Najpierw możesz użyć tylko tego atrybutu" oninvalid "

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

Lub możesz użyć z atrybutem "oninput"

<input id="userid" type="text or others" required="" oninvalid="this.setCustomValidity('Hello Username cant be Blank!')" oninput="setCustomValidity('')">
 10
Author: Obaidul Haque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-05 21:31:36

Najprostszym i najczystszym sposobem, jaki znalazłem, jest użycie atrybutu data do przechowywania niestandardowego błędu. Przetestuj węzeł pod kątem ważności i poradź sobie z błędem za pomocą niestandardowego kodu html. Tutaj wpisz opis obrazka

Le javascript

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

I jakiś super HTML5

<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
 9
Author: Collin White,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-17 19:19:49

Mam prostsze rozwiązanie tylko waniliowe js:

Dla pól wyboru:

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

Dla wejść:

document.getElementById("id").oninvalid = function () {
    this.setCustomValidity(this.value ? '' : 'My message');
};
 1
Author: bernhardh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-18 12:57:44

Dostosowując odpowiedź Salar do JSX i Reacta, zauważyłem, że React Select nie zachowuje się tak jak Pole <input/> dotyczące walidacji. Najwyraźniej kilka obejść jest potrzebnych, aby pokazać tylko niestandardową wiadomość i nie pokazywać jej w niewygodnych czasach.

Poruszyłem tutaj problem , jeśli to w czymś pomoże. tutaj jest CodeSandbox z działającym przykładem, a najważniejszy kod znajduje się tutaj:

Witam.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}
      />
    );
  }
}
 0
Author: GuiRitter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-24 14:23:37

Ok, oninvalid działa dobrze, ale wyświetla błąd, nawet jeśli użytkownik wprowadził poprawne dane. Więc użyłem poniżej, aby go rozwiązać, mam nadzieję, że będzie działać również dla Ciebie,

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

 0
Author: Umesh Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-28 11:14:43