How to properly validate input values with React.JS?

前端 未结 9 1090
孤城傲影
孤城傲影 2020-12-22 19:07

I have a simple form. All of the components and state are held in the Page component. There are 2 display headers and 3 input fields. The first input is supposed to be text,

9条回答
  •  离开以前
    2020-12-22 19:50

    Sometimes you can have multiple fields with similar validation in your application. In such a case I recommend to create common component field where you keep this validation.

    For instance, let's assume that you have mandatory text input in a few places in your application. You can create a TextInput component:

    constructor(props) {
        super(props); 
        this.state = {
            touched: false, error: '', class: '', value: ''
        }
    }
    
    onValueChanged = (event) => {
        let [error, validClass, value] = ["", "", event.target.value];
    
        [error, validClass] = (!value && this.props.required) ? 
            ["Value cannot be empty", "is-invalid"] : ["", "is-valid"]
    
        this.props.onChange({value: value, error: error});
    
        this.setState({
            touched: true,
            error: error,
            class: validClass,
            value: value
        })
    }
    
    render() {
        return (
            
    {this.state.error ?
    {this.state.error}
    : null }
    ) }

    And then you can use such a component anywhere in your application:

    constructor(props) {
        super(props);
        this.state = {
            user: {firstName: '', lastName: ''},
            formState: {
                firstName: { error: '' },
                lastName: { error: '' }
            }
        }
    }
    
    onFirstNameChange = (model) => {
        let user = this.state.user;
        user.firstName = model.value;
    
        this.setState({
            user: user,
            formState: {...this.state.formState, firstName: { error: model.error }}
        })
    }
    
    onLastNameChange = (model) => {
        let user = this.state.user;
        user.lastName = model.value;
    
        this.setState({
            user: user,
            formState: {...this.state.formState, lastName: { error: model.error }}
        })
    }
    
    
    onSubmit = (e) => {
       // submit logic
    }
    
    
    render() {
        return (
            
    {this.state.formState.firstName.error || this.state.formState.lastName.error ? : } ) }

    Benefits:

    • You don't repeat your validation logic
    • Less code in your forms - it is more readable
    • Other common input logic can be kept in component
    • You follow React rule that component should be as dumb as possible

    Ref. https://webfellas.tech/#/article/5

提交回复
热议问题