最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make a field or all fields required in React - Stack Overflow

programmeradmin0浏览0评论

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}
/>

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?

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}
/>

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?

Share Improve this question asked Jul 13, 2020 at 21:39 Samurai JackSamurai Jack 3,1359 gold badges36 silver badges59 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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

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="[email protected]"
          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/npm/[email protected]/dist/semantic.min.css" /><script src="https://cdnjs.cloudflare./ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare./ajax/libs/semantic-ui-react/0.88.2/semantic-ui-react.min.js"></script><div id="root"></div>

You need to add your own validation to check if any of the inputs are empty or not when submit button is clicked if any input is empty show an alert.

This is not an inbuilt functionality you need to add the code for validation and alert yourself.

发布评论

评论列表(0)

  1. 暂无评论