HTML5 form required attribute. Set custom validation message?

前端 未结 14 1686
你的背包
你的背包 2020-11-22 01:26

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

14条回答
  •  再見小時候
    2020-11-22 01:59

    Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an 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 (
          
    e.target.setCustomValidity("")} onInvalid={e => e.target.setCustomValidity("foo")} /> ); } }

    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 (
          
                            
        
    提交评论

提交回复
热议问题