在React中创建一个字段或所有必需的字段 [英] Make a field or all fields required in React

查看:42
本文介绍了在React中创建一个字段或所有必需的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的输入字段:

I have an input field like this:

<Form.Field
  name="contactName"
  className=""
  control={Input}
  label="Contact Name"
  placeholder="Contact Name"
  value={this.state.contactName || ''}
  onChange={this.onChange}
/>

,我想使其成为必需,因此应该添加 required 属性,现在看起来像这样:

and I want to make it required so for that it should be add required attribute and now looks like this:

<Form.Field
  name="contactName"
  className=""
  control={Input}
  label="Contact Name"
  placeholder="Contact Name"
  value={this.state.contactName || ''}
  onChange={this.onChange}
  required
/>

我注意到它还在输入标题附近添加了一个红色星号.问题在于用户仍然可以单击提交"按钮,并且他们将不知道该条目未创建(他们不检查网络以查看呼叫失败).

I noticed that it also adds a red asterisk near the input's title. The problem is that the user can still click the submit button and they will not know that the entry was not created (they don't check the network to see the call failed).

如果未引入所需数据,是否有办法使无法提交?还像弹出/悬停这样说它需要数据吗?

Is there a way to make it impossible to submit if the required data is not introduced? Also something like a popup/hover saying that it requires data?

推荐答案

假设您使用语义UI来设置组件样式,则可以使用< Form的 error 属性.如果表单无效,请输入字段/> 引发错误.

Assuming you use Semantic UI to style your component, you can make use of error prop of your <Form.Field /> to raise an error if form is not valid.

要跟踪该表格是否有效,可以使用您的状态.作为一种选择,您可以将 Submit 按钮的 disabled 属性设置为等于状态变量,该状态变量指示表单是否有效.

To keep track of whether the form is valid, you may use your state. As an option you may set disabled property of Submit button equal to the state variable indicating whether the form is valid.

最基本的形式验证(以匹配一个大写字母和小写字母的模式),您可以在下面的实时演示中找到

The very basic form validation (to match the pattern of one capital letter followed by lowercase letters) you may find in the following live-demo:

const { Component } = React,
      { render } = ReactDOM,
      { Form, Input, Button } = semanticUIReact

const rootNode = document.getElementById('root')

class App extends Component {

  state = {
    submitAttempted: false,
    isValid: {
      contactName: false,
      contactPhone: false,
      contactMail: false
    }
  }
  
  validateInput = (name,value) => { 
    switch(name){
      case 'contactName' : {
        if(/^[A-Z][a-z]+$/.test(value)){
          return true
        } else return false
      }
      case 'contactPhone' : {
        if(/^\d+$/.test(value)){ 
          return true
        } else return false
      }
      case 'contactMail' : {
        if(/^\w+@\w+\.\w{1,4}$/i.test(value)){
          return true
        } else return false
      }
      default: return false
    }
  }    

  onChange = ({target:{name,value}}) => 
    this.setState({
      [name]: value,
      isValid: {
        ...this.state.isValid,
        [name]: this.validateInput(name, value)
      }
    })
  
  onSubmit = e => {
    e.preventDefault()
    this.setState({
      submitAttempted: true
    })
    Object.values(this.state.isValid).every(Boolean) &&
    console.log(this.state.contactName, this.state.contactPhone, this.state.contactMail)
  }

  render(){    
    return (
      <Form onSubmit={this.onSubmit} >
        <Form.Field
          name="contactName"
          className=""
          control={Input}
          label="Contact Name"
          placeholder="Contact Name"
          value={this.state.contactName || ''}
          onChange={this.onChange}
          required
          error={(
            (this.state.submitAttempted && !this.state.isValid.contactName) &&
            {
              content: 'Valid contact name should contain upper-case letters followed by lower-case letters',
              pointing: 'below'
            }
          )}
        />
        <Form.Field
          name="contactPhone"
          className=""
          control={Input}
          label="Contact Phone"
          placeholder="Contact Phone"
          value={this.state.contactPhone || ''}
          onChange={this.onChange}
          required
          error={(
            (this.state.submitAttempted && !this.state.isValid.contactPhone) && 
            {
              content: 'Valid phone, should contain numbers only',
              pointing: 'below'
            }
          )}
        />
        <Form.Field
          name="contactMail"
          className=""
          control={Input}
          label="Contact Mail"
          placeholder="example@hello.com"
          value={this.state.contactMail || ''}
          onChange={this.onChange}
          required
          error={(
            (this.state.submitAttempted && !this.state.isValid.contactMail) &&
            {
              content: 'Valid e-mail format should be fulfilled',
              pointing: 'below'
            }
          )}
        />
        <Button 
          type="submit"
          disabled={
            this.state.submitAttempted && 
            !Object.values(this.state.isValid).every(Boolean)
          }
        >
          Submit
        </Button>
      </Form>
    )
  }

}

render (
  <App />,
  rootNode
)

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui-react/0.88.2/semantic-ui-react.min.js"></script><div id="root"></div>

这篇关于在React中创建一个字段或所有必需的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆