【问题标题】:How to invalidate a TextField in Material UI如何在 Material UI 中使 TextField 无效
【发布时间】:2016-06-24 09:49:12
【问题描述】:

我正在使用 TextField 组件来捕获电话号码。当用户键入时,如果它不是数字或者它不遵循格式并显示错误文本,我想使该条目无效。目前即使不触摸该字段也会显示 errorText。我怎样才能实现这种行为?

非常感谢任何帮助。

【问题讨论】:

    标签: javascript validation material-ui textfield


    【解决方案1】:

    从 0.20.1 开始,您可以使用 helperText 和 error 道具

    <TextField 
        hintText="Phone"
        error ={this.state.errorText.length === 0 ? false : true }
        floatingLabelText="Phone"
        name="phone"
        helperText={this.state.errorText}
        onChange={this.onChange.bind(this)}/>
    

    【讨论】:

    • 谢谢!这对我有用,但我改变了一点,使用了error={!!this.state.errorText}
    【解决方案2】:

    扩展Larry答案,将errorText设置为状态属性(下例中的errorText)。当 TextField 中的值发生变化时,验证条目并设置属性(errorText)的值来显示和隐藏错误。

    class PhoneField extends Component
      constructor(props) {
        super(props)
        this.state = { errorText: '', value: props.value }
      }
      onChange(event) {
        if (event.target.value.match(phoneRegex)) {
          this.setState({ errorText: '' })
        } else {
          this.setState({ errorText: 'Invalid format: ###-###-####' })
        }
      }
      render() {
        return (
          <TextField hintText="Phone"
            floatingLabelText="Phone"
            name="phone"
            errorText= {this.state.errorText}
            onChange={this.onChange.bind(this)}
          />
        )
      }
    }
    

    【讨论】:

    • 这不再起作用了。 errorText 被 helperText 和布尔 error 替换以将其显示为错误文本。
    • 对 TextField 设置错误不会使 TextField 内的输入无效,也不会阻止表单提交。这只是一种 UI 行为,没有真正的功能。
    【解决方案3】:

    如果errorText为空字符串“”,则不会显示。所以,在 getInitialState() 中设置它。

    【讨论】:

      【解决方案4】:

      材质-UI v3.9.3 工作版本:

      class UserProfile extends React.Component {
        constructor(props) {
          super(props);
          this.state = { helperText: '', error: false };
        }
      
        onChange(event) {
          if (event.target.value.length > 2) {
            this.setState({ helperText: '', error: false });
          } else {
            this.setState({ helperText: 'Invalid format', error: true });
          }
        }
      
        render() {
          return (
      
                         <TextField
                            helperText={this.state.helperText}
                            onChange={this.onChange.bind(this)}
                            error={this.state.error}
                            required
                            id="outlined-required"
                            label="First Name"
                          />
                           );
        }
      

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 2018-02-08
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-29
        相关资源
        最近更新 更多