在ReactJS中单击按钮时执行验证 [英] Perform validation when button is clicked in ReactJS

查看:64
本文介绍了在ReactJS中单击按钮时执行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当单击按钮时,应检查验证是否完成,然后仅表单数据应进入数据库.

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

我想要这样的 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>

推荐答案

因此,为了使它起作用,必须在此进行一些修复.但是我们将很快完成它

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 每个错误的答案

首先,在初始化对象之前,先对对象(newUser)调用forEach.没有定义变量会导致它被...未定义.改掉错误

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

但是,即使我们要解决此问题并交换2的位置,它仍然无法工作.您正在调用函数 forEach 实际上,这是javascript中数组对象的属性,而您的 newUser 是js对象.为了让您可以遍历对象中的键,您将需要默认为普通的for循环

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

这篇关于在ReactJS中单击按钮时执行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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