简体   繁体   English

如何在 Material ui 表单输入字段中添加验证

[英]How to add validation in Material ui form input fields

I have a react functional component built using Material ui form which contains TextField and onChange event is handled in "Container Component".我有一个使用包含TextField的 Material ui 表单构建的反应功能组件,并且onChange事件在“容器组件”中处理。 Below is the form code where i need to add required as client side form validation but, its not working.下面是我需要添加required的表单代码作为客户端表单验证,但它不起作用。 Do i need to add some logic in container component as well?我是否还需要在容器组件中添加一些逻辑?

<form className={classes.container}>
<Grid container item xs={12} alignItems="center">
<TextField
  id="outlined-bare"
  className={classes.textField1}
  defaultValue=""
  required
  margin="normal"
  variant="outlined"
  autoComplete="on"
  InputProps={{ style: { height: 40 } }}
  onChange={(e) => handleChange(e, 'Name')}
/>

and here is event handler in container component like below这是容器组件中的事件处理程序,如下所示

 setInput = (e, source) => {
    e.preventDefault();
    switch  (source) {
        case "Name":
            this.setState({
                ...this.state,
                Name: e.target.value
            })
            break;
    default:
            this.setState({...this.state})
            break;
    }
}

 return (
        <div>
            <Drawer
                route={routes.abc}
                history={this.props.history}
                handleChange={this.setInput}
            />
        </div>
    )

What's wrong, and is missing?有什么问题,遗漏了什么? I am new to ReactJs.我是 ReactJs 的新手。 Kindly suggest.请建议。

With what information is available, I would suggest doing something like the following simplified version:有了可用的信息,我建议执行以下简化版本之类的操作:

Container容器

class Container extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      other_value: '',
    }
  }

  handleChange = (field, value) => {
    this.setState({ [field]: value });
  }

  valid = () => {
    if (!this.state.name) {
      return false;
    }
  }

  submit = () => {
    if (this.valid()) {
      // call your redux submit
    }
  }

  render() {
    return (
      <MyForm
        values={this.state}
        handleChange={this.handleChange}
        submit={this.submit}
      />
    );
  }
}

Form component表单组件

const MyForm = (props) => {
  return (
    <form onSubmit={props.submit}>
      <TextField
        onChange={(e) => props.handleChange('name', e.target.value)}
        value={props.values.name}
        required
      />
      <TextField
        onChange={(e) => props.handleChange('other_value', e.target.value)}
        value={props.values.other_value}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

First, if you are using an onChange on your input, you should also provide its value to insure they remain in-sync.首先,如果您在输入上使用onChange ,您还应该提供其值以确保它们保持同步。

Second, If you want the required prop to have an effect, you should make sure your submit function is called by the form.其次,如果您希望required的道具生效,您应该确保您的提交 function 被表单调用。 The required prop is just passed down to the input element which will get used by the wrapping form (explanation of required) . required的道具只是传递给将被包装form使用的input元素(所需的解释) So if the form isn't the one calling your submit function, required will be ignored.因此,如果表单不是调用您提交 function 的表单,则required将被忽略。

Lastly, I only provided a simple validate function, if you want it to be more comprehensive, just add more checks and return specific errors or an array of errors instead of a simple true or false.最后,我只提供了一个简单的验证 function,如果您希望它更全面,只需添加更多检查并返回特定错误或错误数组,而不是简单的真假。 You could also skip the validation function completely if a simple required check is all you need.如果您只需要简单的必需检查,您也可以完全跳过验证 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM