programing

반응 및 물질적 유의를 통한 양식 검증

prostudy 2022. 4. 9. 08:09
반응형

반응 및 물질적 유의를 통한 양식 검증

나는 현재 재료 UI 구성요소를 사용하여 작성된 양식에 유효성 검사를 추가하려고 한다.나는 그것이 작동하고 있지만 문제는 내가 현재 그것을 하고 있는 방법의 유효성 검사 기능이 입력의 모든 상태 변화(즉, 입력되는 모든 문자)에 대해 현재 호출되고 있다는 것이다.그러나 나는 타이핑이 중지된 후에만 유효성 검사를 수행하기를 원한다.

현재 코드 지정:

class Form extends React.Component {

    state = {open: false, email: '', password: '', email_error_text: null, password_error_text: null, disabled: true};

    handleTouchTap() {
        this.setState({
            open: true,
        });
    }

    isDisabled() {
        let emailIsValid = false;
        let passwordIsValid = false;

        if (this.state.email === "") {
            this.setState({
                email_error_text: null
            });
        } else {
            if (validateEmail(this.state.email)) {
                emailIsValid = true
                this.setState({
                    email_error_text: null
                });
            } else {
                this.setState({
                    email_error_text: "Sorry, this is not a valid email"
                });
            }
        }

        if (this.state.password === "" || !this.state.password) {
            this.setState({
                password_error_text: null
            });
        } else {
            if (this.state.password.length >= 6) {
                passwordIsValid = true;
                this.setState({
                    password_error_text: null
                });
            } else {
                this.setState({
                    password_error_text: "Your password must be at least 6 characters"
                });
            }
        }

        if (emailIsValid && passwordIsValid) {
            this.setState({
                disabled: false
            });
        }
    }

    changeValue(e, type) {
        const value = e.target.value;
        const nextState = {};
        nextState[type] = value;
        this.setState(nextState, () => {
            this.isDisabled()
        });
    }

    login() {
        createUser(this.state.email, this.state.password);
        this.setState({
            open: false
        });
    }

    render() {

        let {open, email, password, email_error_text, password_error_text, disabled} = this.state;

        const standardActions = (
            <FlatButton
                containerElement={<Link to="/portal" />}
                disabled={this.state.disabled}
                label="Submit"
                onClick={this.login.bind(this)} 
            />
        );

        return (
            <div style={styles.container}>
                <Dialog
                    open={this.state.open}
                    title="Enter Your Details to Login"
                    actions={standardActions}
                >
                    <span className="hint--right hint--bounce" data-hint="Enter in your email address">
                        <TextField
                            hintText="Email"
                            floatingLabelText="Email"
                            type="email"
                            errorText={this.state.email_error_text}
                            onChange={e => this.changeValue(e, 'email')} 
                        />
                    </span>
                    <br />
                    <span className="hint--right hint--bounce" data-hint="Enter your password">
                        <TextField
                            hintText="Password"
                            floatingLabelText="Password"
                            type="password"
                            errorText={this.state.password_error_text}
                            onChange={e => this.changeValue(e, 'password')} 
                        />
                    </span>
                </Dialog>
                <h1>VPT</h1>
                <h2>Project DALI</h2>
                <RaisedButton
                    label="Login"
                    primary={true}
                    onTouchTap={this.handleTouchTap.bind(this)} 
                />
            </div>
        );
    }
}

export default Form;

코드를 크게 변경하지 않고 원하는 기능을 달성할 수 있는 방법이 있는가, 아니면 완전히 리팩터링할 필요가 있는가?

수표는 일정 지연 후에 해야 하는 겁니까?내가 생각하기에 대부분의 상황에서 충분하다고 생각하는 해결책은 당신의 코드를 조금 나누는 것이다.방아쇠를 당기지 마라.isDisabled()에서 기능하다.changedValue(). 대신, 그 대신에 그것을 실행시키도록 하라.onBlur대신 사건이야

다음을 시도해 보십시오.

<TextField
  hintText="Password"
  floatingLabelText="Password"
  type="password"
  errorText={this.state.password_error_text}
  onChange={e => this.changeValue(e, 'password')}
  onBlur={this.isDisabled} 
/>

그리고 당신의 기능은 다음과 같이 된다.

changeValue(e, type) {
    const value = e.target.value;
    const nextState = {};
    nextState[type] = value;
    this.setState(nextState);
}

현재 Material-UI 버전은errorText그러나 오류를 표시하고 재료-UI의 TextField에 유효성 검사를 적용하는 데 사용할 수 있는 방법이 있다.

우리는 그것을 사용한다.error(Boolean) 오류가 있는지 여부를 나타내는 속성.추가적으로 오류 텍스트 사용 표시helperTextMaterial-UI에서 TextField 속성은 표시하려는 오류 텍스트를 입력하십시오.

다음과 같이 하십시오.

<TextField
  value={this.state.text}
  onChange={event => this.setState({ text: event.target.value })}
  error={text === ""}
  helperText={text === "" ? 'Empty!' : ' '}
/>

가장 간단한 것은 전화를 거는 것이다.form.reportValidity().form부르면 얻을 수 있다.event.currentTarget.form.

내가 만든 이 라이브러리는 필드 검증과 관련된 모든 것을 처리하며 재료의 UI 구성 요소도 지원한다...

필드를 검증하려면 필드 구성요소를 줄 바꿈하기만 하면 되며, 완료됨...수동으로 상태를 관리하는 데 많은 노력을 기울여야 한다.

<Validation group="myGroup1"
    validators={[
            {
             validator: (val) => !validator.isEmpty(val),
             errorMessage: "Cannot be left empty"
            }, ...
        }]}>
            <TextField value={this.state.value}
                       className={styles.inputStyles}
                       style={{width: "100%"}}
                       onChange={
                        (evt)=>{
                          console.log("you have typed: ", evt.target.value);
                        }


     }/>

온블러 텍스트 필드 이벤트를 사용할 수 있다.그것은 입력이 포커스를 느슨하게 할 때 촉발된다.

참조URL: https://stackoverflow.com/questions/36911760/form-validation-with-react-and-material-ui

반응형