Perform validation when button is clicked in ReactJS

拜拜、爱过 提交于 2020-08-10 20:00:47

问题


When the button is clicked the validation should be checked if validation is complete then only the form data should go to database.

I want it like this https://codesandbox.io/s/7rmhp?file=/src/Components/FormComponent.js:1768-1773

I am facing an error:

:Type Error: Cannot read property 'forEach' of undefined
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
this.validateFirstName = this.validateFirstName.bind(this);
this.validateLastName = this.validateLastName.bind(this);
this.validatebusinessName = this.validatebusinessName.bind(this);
this.validateEmailAddress = this.validateEmailAddress.bind(this);
this.validatephonenumber = this.validatephonenumber.bind(this);
this.validateaddress1 = this.validateaddress1.bind(this);
this.validateaddress2 = this.validateaddress2.bind(this);
this.validatecity = this.validatecity.bind(this);
// this.validatezipcode = this.validatezipcode.bind(this);
this.validatePassword = this.validatePassword.bind(this);
this.validatePasswordConfirmation = this.validatePasswordConfirmation.bind(
    this
);
this.validateField = this.validateField.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}

onChange(e) {
    this.setState({ [e.target.name]: e.target.value })
}
 

validateField(name) {
    let isValid = false;

    if (name === "first_name") isValid = this.validateFirstName();
    else if (name === "business_name") isValid = this.validatebusinessName();

    else if (name === "last_name") isValid = this.validateLastName();
    else if (name === "emailAddress") isValid = this.validateEmailAddress();
    else if (name === "phone_number") isValid = this.validatephonenumber();
    else if (name === "address1") isValid = this.validateaddress1();
    else if (name === "address2") isValid = this.validateaddress2();
    else if (name === "city") isValid = this.validatecity();
    // else if (name === "zipcode") isValid = this.validatezipcode();
    else if (name === "password") isValid = this.validatePassword();
    else if (name === "passwordConfirmation")
        isValid = this.validatePasswordConfirmation();
    return isValid;
}

handleBlur(event) {
    const { name } = event.target;

    this.validateField(name);
    return;
}
onSubmit(e) {
    e.preventDefault()
    let isValid = true;
    newUser.forEach(field => {
        isValid = this.validateField(field) && isValid;
    });

    if (isValid) this.setState({ isFormSubmitted: true });
    else this.setState({ isFormSubmitted: false });

    

    const newUser = {
        business_name: this.state.business_name,
        therapeutic_area: this.state.therapeutic_area,
        disease: this.state.disease,
        first_name: this.state.first_name,
        last_name: this.state.last_name,
        email: this.state.email,
        phone_number: this.state.phone_number,
        cell_number: this.state.cell_number,
        fax_number: this.state.fax_number,
        address1: this.state.address1,
        address2: this.state.address2,
        city: this.state.city,
        state: this.state.state,
        zipcode: this.state.zipcode,
        country: this.state.country,
        region: this.state.region,
        password: this.state.password
    }

    // let isValid = true;
    // newUser.forEach(field => {
    //     isValid = this.validateField(field) && isValid;
    // });

    // if (isValid) this.setState({ isFormSubmitted: true });
    // else this.setState({ isFormSubmitted: false });

    // return this.state.isFormSubmitted;


    register(newUser).then(res => {
        this.props.history.push(`/login`)
    })

    
}

validateFirstName() {
    let firstNameError = "";
    const value = this.state.first_name;
    if (value.trim() === "") firstNameError = "First Name is required";

    this.setState({
        firstNameError
    });
    return firstNameError === "";
}

validatebusinessName() {
    let businessNameError = "";
    const value = this.state.business_name;
    if (value.trim() === "") businessNameError = "business Name is required";

    this.setState({
        businessNameError
    });
    return businessNameError === "";
}

validateLastName() {
    let lastNameError = "";
    const value = this.state.last_name;
    if (value.trim() === "") lastNameError = "Last Name is required";

    this.setState({
        lastNameError
    });
    return lastNameError === "";
}
validateEmailAddress() {
    let emailAddressError = "";
    const value = this.state.email;
    if (value.trim === "") emailAddressError = "Email Address is required";
    else if (!emailValidator.test(value))
        emailAddressError = "Email is not valid";

    this.setState({
        emailAddressError
    });
    return emailAddressError === "";
}

validatephonenumber() {
    let phonenumberError = "";
    const value = this.state.phone_number;
    if (value.trim === "") phonenumberError = "Phone number is required";
    else if (!numberValidator.test(value))
        phonenumberError = "phone number is not valid"
}
validateaddress1() {
    let address1Error = "";
    const value = this.state.address1;
    if (value.trim() === "") address1Error = "address1 is required";

    this.setState({
        address1Error
    });
    return address1Error === "";
}
validateaddress2() {
    let address2Error = "";
    const value = this.state.address2;
    if (value.trim() === "") address2Error = "address2 is required";

    this.setState({
        address2Error
    });
    return address2Error === "";
}
validatecity() {
    let cityError = "";
    const value = this.state.city;
    if (value.trim() === "") cityError = "city is required";

    this.setState({
        cityError
    });
    return cityError === "";
}
// validatezipcode() {
//     let zipcodeError = "";
//     const value = this.state.zipcode;
//     if (value.trim() === "") zipcodeError = "city is required";

//     this.setState({
//         zipcodeError
//     });
//     return zipcodeError === "";
// }
validatePassword() {
    let passwordError = "";
    const value = this.state.password;
    if (value.trim === "") passwordError = "Password is required";
    else if (!passwordValidator.test(value))
        passwordError =
            "Password must contain at least 8 characters, 1 number, 1 upper and 1 lowercase!";

    this.setState({
        passwordError
    });
    return passwordError === "";
}

validatePasswordConfirmation() {
    let passwordConfirmationError = "";
    if (this.state.password !== this.state.passwordConfirmation)
        passwordConfirmationError = "Password does not match Confirmation";

    this.setState({
        passwordConfirmationError
    });
    return passwordConfirmationError === "";
}
selectCountry(val) {
    this.setState({ country: val });
}

selectRegion(val) {
    this.setState({ state: val });
}
cellnumber(value) {
    
    this.setState({cell_number: value});
    
}
phonenumber(value) {

    this.setState({ phone_number: value });

}
faxnumber(value) {

    this.setState({ fax_number: value });

}
componentDidMount() {
    fetch(
        "http://localhost:3000/list"
    )
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data.value);
            let teamsFromApi = data.map(team => {
                return { value: team, display: team };
            });
            this.setState({
                teams: [
                    {
                        value: "",
                        display:
                            "(Select your favourite team)"
                    }
                ].concat(teamsFromApi)
            });
        })
        .catch(error => {
            console.log(error);
        });


    fetch(
        "http://localhost:3000/dislist"
    )
        .then(response => {
            return response.json();
        })
        .then(data => {
            let diseasesFromApi = data.map(dis => {
                return { value: dis, display: dis };
            });
            this.setState({
                diseases: [
                    {
                        value: "",
                        display:
                            "(Select your favourite team)"
                    }
                ].concat(diseasesFromApi)
            });
        })
        .catch(error => {
            console.log(error);
        });
}


render() {
    const { country, state } = this.state;
    return (
       
<form onSubmit={this.onSubmit}>
  
    <div className="row">
        <div className="col">
            
               
            <div className="form-group">
                <label htmlFor="address2">Address2</label>
                <input
                    type="text"
                    className="form-control"
                    name="address2"
                    placeholder=""
                    value={this.state.address2}
                    onChange={this.onChange}
                    onBlur={this.handleBlur}
                    autoComplete="off"
                />
                {this.state.address2Error && (
                    <span className="errorMsg">{this.state.address2Error}</span>
                )}
            </div>
        </div>            

        <div className="col">          
            <div className="form-group">
                <label htmlFor="city">City</label>
                <input
                    type="text"
                    className="form-control"
                    name="city"
                    placeholder=""
                    value={this.state.city}
                    onChange={this.onChange}
                    onBlur={this.handleBlur}
                    autoComplete="off"
                />
                {this.state.cityError && (
                    <span className="errorMsg">{this.state.cityError}</span>
                )}
            </div>
        </div>
    </div>                
    {/* <div className="form-group">
        <label htmlFor="sta">State</label>
        <input
            type="text"
            className="form-control"
            name="state"
            placeholder=""
            value={this.state.state}
            onChange={this.onChange}
        />
    </div> */}

    <div className="row">
        <div className="col">
            <div className="form-group">
                <label htmlFor="zipcode">Zipcode</label>
                <input
                    type="text"
                    className="form-control"
                    name="zipcode"
                    placeholder=""
                    value={this.state.zipcode}
                    onChange={this.onChange}
                    onBlur={this.handleBlur}
                    autoComplete="off"
                />
                {this.state.zipcodeError && (
                    <span className="errorMsg">{this.state.zipcodeError}</span>
                )}
            </div>
        </div>    
        <div className="col">
            <div class="form-group">
               
                
                    <label for="exampleFormControlSelect3">Country</label>
                    <CountryDropdown
                        defaultOptionLabel="Plase Select a country"
                        value={country}
                        onChange={(val) => this.selectCountry(val)} 
                        className="form-control"/>
                        </div>
        </div>
    </div>
    <div className="row">
        <div className="col">                  
            <div class="form-group">
                <label for="exampleFormControlSelect4">State</label>
                    <RegionDropdown
                        blankOptionLabel="No country selected."
                        defaultOptionLabel="Now select a region"
                        country={country}
                        value={state}
                        onChange={(val) => this.selectRegion(val)} 
                        className="form-control"/>
                
            </div>
        </div>
        <div className="col">          
            <div className="form-group">
                <label htmlFor="password">Password</label>
                {/* <input
                    type="password"
                    className="form-control"
                    name="password"
                    placeholder="Password"
                    value={this.state.password}
                    onChange={this.onChange}
                /> */}
                <input
                    type="password"
                    placeholder="Password"
                    name="password"
                    className="form-control"
                    value={this.state.password}
                    onChange={this.onChange}
                    onBlur={this.handleBlur}
                    autoComplete="off"
                />
                
                {this.state.passwordError && (
                    <div className="errorMsg">{this.state.passwordError}</div>
                )}
            </div>
        </div>
    </div>                
        <div className="form-group">
         <label>Confirm Password</label>   
        <input
            type="password"
            placeholder="Confirm Password"
            name="passwordConfirmation"
            className="form-control"
            value={this.state.passwordConfirmation}
            onChange={this.onChange}
            onBlur={this.handleBlur}
            autoComplete="off"
        />
        
        {this.state.passwordConfirmationError && (
            <div className="errorMsg">
                {this.state.passwordConfirmationError}
            </div>
        )}
        </div>
    <button
        type="submit"
        className="btn but  btn-block"
    >
        Register
    </button>
</form>

回答1:


So there are a few things that has to be fixed here in order to make it work. But we will have it done in no time

#1 The for each error

First of all you are calling the forEach on the object (newUser) before you have initialized it. Not having defined a variable leads to it being... undefined. Ergo the error

Cannot read property 'forEach' of undefined thanks in advance

However, even if we were to fix that and swapped the place of the 2, it still would not work. You are calling the function forEach that is a property of the array object in javascript when in fact your newUser is a js object. In order for you to loop over the keys in your object you are going to want to default to a normal for loop looking like this

for(var key in newUser){
  isValid = this.validateField(key) && isValid;
}

Hopefully this fixes your problem



来源:https://stackoverflow.com/questions/62512262/perform-validation-when-button-is-clicked-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!