Reactjs - Form input validation

前端 未结 9 1931
悲哀的现实
悲哀的现实 2020-11-28 20:04

My Contact page form is as follows,

<
相关标签:
9条回答
  • 2020-11-28 20:34

    Might be late to answer - if you don't want to modify your current code a lot and still be able to have similar validation code all over your project, you may try this one too - https://github.com/vishalvisd/react-validator.

    0 讨论(0)
  • 2020-11-28 20:37

    We have plenty of options to validate the react js forms. Maybe the npm packages have some own limitations. Based up on your needs you can choose the right validator packages. I would like to recommend some, those are listed below.

    • react-form-input-validation
    • redux-form

    If anybody knows a better solution than this, please put it on the comment section for other people references.

    0 讨论(0)
  • 2020-11-28 20:37

    Try this, example, the required property in below input tag will ensure that the name field should be submitted empty.

    <input type="text" placeholder="Your Name" required />
    
    0 讨论(0)
  • 2020-11-28 20:45

    You should avoid using refs, you can do it with onChange function.

    On every change, update the state for the changed field.

    Then you can easily check if that field is empty or whatever else you want.

    You could do something as follows :

        class Test extends React.Component {
            constructor(props){
               super(props);
          
               this.state = {
                   fields: {},
                   errors: {}
               }
            }
        
            handleValidation(){
                let fields = this.state.fields;
                let errors = {};
                let formIsValid = true;
    
                //Name
                if(!fields["name"]){
                   formIsValid = false;
                   errors["name"] = "Cannot be empty";
                }
          
                if(typeof fields["name"] !== "undefined"){
                   if(!fields["name"].match(/^[a-zA-Z]+$/)){
                      formIsValid = false;
                      errors["name"] = "Only letters";
                   }        
                }
           
                //Email
                if(!fields["email"]){
                   formIsValid = false;
                   errors["email"] = "Cannot be empty";
                }
          
                if(typeof fields["email"] !== "undefined"){
                   let lastAtPos = fields["email"].lastIndexOf('@');
                   let lastDotPos = fields["email"].lastIndexOf('.');
    
                   if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
                      formIsValid = false;
                      errors["email"] = "Email is not valid";
                    }
               }  
    
               this.setState({errors: errors});
               return formIsValid;
           }
            
           contactSubmit(e){
                e.preventDefault();
    
                if(this.handleValidation()){
                   alert("Form submitted");
                }else{
                   alert("Form has errors.")
                }
          
            }
        
            handleChange(field, e){         
                let fields = this.state.fields;
                fields[field] = e.target.value;        
                this.setState({fields});
            }
        
            render(){
                return (
                    <div>           
                       <form name="contactform" className="contactform" onSubmit= {this.contactSubmit.bind(this)}>
                            <div className="col-md-6">
                              <fieldset>
                                   <input ref="name" type="text" size="30" placeholder="Name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                                   <span style={{color: "red"}}>{this.state.errors["name"]}</span>
                                  <br/>
                                 <input refs="email" type="text" size="30" placeholder="Email" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                                 <span style={{color: "red"}}>{this.state.errors["email"]}</span>
                                 <br/>
                                 <input refs="phone" type="text" size="30" placeholder="Phone" onChange={this.handleChange.bind(this, "phone")} value={this.state.fields["phone"]}/>
                                 <br/>
                                 <input refs="address" type="text" size="30" placeholder="Address" onChange={this.handleChange.bind(this, "address")} value={this.state.fields["address"]}/>
                                 <br/>
                             </fieldset>
                          </div>
              
                      </form>
                    </div>
              )
            }
        }
    
        React.render(<Test />, document.getElementById('container'));
    
    

    In this example I did the validation only for email and name, but you have an idea how to do it. For the rest you can do it self.

    There is maybe a better way, but you will get the idea.

    Here is fiddle.

    Hope this helps.

    0 讨论(0)
  • 2020-11-28 20:49

    With React Hook, form is made super easy (React Hook Form: https://github.com/bluebill1049/react-hook-form)

    i have reused your html markup.

    import React from "react";
    import useForm from 'react-hook-form';
    
    function Test() {
      const { useForm, register } = useForm();
      const contactSubmit = data => {
        console.log(data);
      };
    
      return (
        <form name="contactform" onSubmit={contactSubmit}>
          <div className="col-md-6">
            <fieldset>
              <input name="name" type="text" size="30" placeholder="Name" ref={register} />
              <br />
              <input name="email" type="text" size="30" placeholder="Email" ref={register} />
              <br />
              <input name="phone" type="text" size="30" placeholder="Phone" ref={register} />
              <br />
              <input name="address" type="text" size="30" placeholder="Address" ref={register} />
              <br />
            </fieldset>
          </div>
          <div className="col-md-6">
            <fieldset>
              <textarea name="message" cols="40" rows="20" className="comments" placeholder="Message" ref={register} />
            </fieldset>
          </div>
          <div className="col-md-12">
            <fieldset>
              <button className="btn btn-lg pro" id="submit" value="Submit">
                Send Message
              </button>
            </fieldset>
          </div>
        </form>
      );
    }
    
    0 讨论(0)
  • 2020-11-28 20:54

    Try powerform-react . It is based upon powerform which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.

    Checkout this simple form that uses powerform-react

    There is also a complex example.

    0 讨论(0)
提交回复
热议问题