【问题标题】:Perform validation when button is clicked in ReactJS在 ReactJS 中单击按钮时执行验证
【发布时间】:2020-10-12 04:29:04
【问题描述】:

当点击按钮时,如果验证完成,则应该检查验证,然后只有表单数据应该进入数据库。

我想要这样https://codesandbox.io/s/7rmhp?file=/src/Components/FormComponent.js:1768-1773

我遇到了一个错误:

: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>

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    因此,为了使其正常工作,必须在此处修复一些问题。但是我们很快就会完成它

    #1 每个错误的原因

    首先,您在初始化对象 (newUser) 之前调用了 forEach。没有定义变量会导致它……未定义。因此错误

    Cannot read property 'forEach' of undefined thanks in advance

    但是,即使我们要解决这个问题并交换 2 的位置,它仍然无法正常工作。您正在调用函数 forEach,它是 javascript 中数组对象的一个​​属性,而实际上您的 newUser 是一个 js 对象。为了让您循环遍历对象中的键,您需要默认为正常的 for 循环,如下所示

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

    希望这能解决您的问题

    【讨论】:

    • 如果您发现答案有帮助,请考虑对其进行投票,以便下一个遇到相同问题的人可以看到以下解决方案有效。堆栈溢出是一个持久的论坛。最好的问候。
    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2014-04-20
    • 2015-10-09
    相关资源
    最近更新 更多