HTML5 форма обязательный атрибут.Установить пользовательское сообщение проверки? - PullRequest
274 голосов
/ 11 марта 2011

У меня есть следующая форма 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"/>

В настоящее время, когда я нажимаю клавишу ввода, когда они оба пусты, появляется всплывающее окно с надписью «Пожалуйста, заполните это поле».Как бы изменить это сообщение по умолчанию на «Это поле нельзя оставить пустым»?

РЕДАКТИРОВАТЬ: Также обратите внимание, что сообщение об ошибке в поле типа пароля просто *****.Чтобы воссоздать это, введите имя пользователя и нажмите «Отправить».

РЕДАКТИРОВАТЬ : я использую Chrome 10 для тестирования.Пожалуйста, сделайте то же самое

Ответы [ 14 ]

1 голос
/ 19 февраля 2019

Решение для предотвращения сообщений об ошибках Google Chrome при вводе каждого символа:

<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>
1 голос
/ 28 августа 2018

Хорошо, oninvalid работает хорошо, но показывает ошибку, даже если пользователь ввел правильные данные. Поэтому я использовал ниже, чтобы заняться этим, надеюсь, это будет работать и для вас,

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

0 голосов
/ 16 мая 2019

Можно легко обработать, просто поставив 'title' с полем:

<input type="text" id="username" required title="This field can not be empty"  />
0 голосов
/ 24 мая 2018

Адаптируя Салар ответ на JSX и React, я заметил, что React Select не ведет себя так же, как поле <input/> в отношении проверки.По-видимому, необходимо несколько обходных путей, чтобы показать только пользовательское сообщение и не показывать его в неудобное время.

Я поднял проблему здесь , если это поможет. Здесь - это 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}
      />
    );
  }
}
...