【问题标题】:I have a validate function in React/Reactstrap which I'm applying to multiple fields, however all fields are validating at the same time我在 React/Reactstrap 中有一个验证函数,我将其应用于多个字段,但是所有字段都在同时验证
【发布时间】:2020-02-26 23:12:07
【问题描述】:

到目前为止,这是我的代码(只是相关部分,我还使用availity-reactstrap-validation 仅供参考):

export default class CustomModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            toolPlatform: [],
            workstream: [],
            opsarea: [],
            campus: [],
            riskcat: [],
            activeItem: this.props.activeItem,
        validate: {
            textState: '',
        },
        };
    }

validateText(e) {
        const textRex = /^(?!\s*$).+/;
        const { validate } = this.state
            if (textRex.test(e.target.value)) {
                validate.textState = 'has-success'
            } else {
                validate.textState = 'has-danger'
            }
            this.setState( {validate})
        };


render() {
        const { toggle, onSave } = this.props;
        return (            
            <Modal isOpen={true} toggle={toggle}>
                <ModalHeader toggle={toggle}> Tool Details </ModalHeader>
                <ModalBody>
                    <AvForm onValidSubmit = {() => onSave(this.state.activeItem)}>
                        <FormGroup>
                            <Label for="title">Title</Label>
                            <AvInput valid 
                                type="text"
                                name="title"
                                value={this.state.activeItem.title}
                                //onChange={this.handleChange}
                                placeholder="Tool Name"
                                valid={ this.state.validate.textState === 'has-success' }
                                invalid={ this.state.validate.textState === 'has-danger' }
                                onChange={ (e) => {
                                    this.validateText(e)
                                    this.handleChange(e)
                                }}
                                required
                            />
                        </FormGroup> 
                        <AvGroup>
                            <Label for="description">Description</Label>
                            <AvInput valid
                                type="text"
                                name="description"
                                value={this.state.activeItem.description}
                                valid={ this.state.validate.textState === 'has-success' }
                                invalid={ this.state.validate.textState === 'has-danger' }
                                placeholder="Tool description"
                                onChange={ (e) => {
                                    this.validateText(e)
                                    this.handleChange(e)
                                }}
                                required
                            />

验证有效,但是当我开始输入其中一个字段时,两个字段同时被验证。这是有道理的,我明白它为什么这样做,但我不能 100% 确定如何更改语法以仅验证我正在输入的字段。

希望这是有道理的!我确信改变是相当基本的,我只是新人,还在学习,所以我不能完全掌握正确的语法。

非常感谢!

【问题讨论】:

  • 您的两个输入字段都引用了相同的验证状态值this.state.validate.textState
  • 你需要将每个字段的值和有效性独立存储在状态中,而不是所有字段的一个状态值
  • @Jackson 是的,我认为这就是问题所在,我只是不确定如何解决它:D
  • 谢谢@Jayce444,你能帮我解决语法问题吗?我一直在疯狂地搜索,但很难找到正确的搜索词,而且我还在学习,我对可用的选项没有很好的掌握
  • @simonk83 基本上 this.state.validate 每个输入字段都有一个属性,当您验证时传入该属性,例如this.validateText(e, "title") 并相应地更新该属性,即 this.setState( {validate: {...validate, [field]:"has-success"}}) 或其他东西。另请注意,您直接在 validateText 函数中改变状态,因为解构不会创建新对象,只是对状态对象的引用,然后您可以直接对其进行更新。确保不要在 React 中改变状态,复制事物

标签: javascript reactjs reactstrap


【解决方案1】:

首先,您的 textState 需要两个不同的字段,否则它们共享相同的:

this.state = {
        data: [],
        toolPlatform: [],
        workstream: [],
        opsarea: [],
        campus: [],
        riskcat: [],
        activeItem: this.props.activeItem,
        validate: {
            textState: {
                title: '',
                description: '',
            },
        },
    };

然后检查 e.target.name 以确定要更新 textState 的哪个字段(您也可以将其作为参数传递给此函数)

validateText ( e ) {
    const textRex = /^(?!\s*$).+/; 

    // If test is true / false
    const fieldTextState = textRex.test( e.target.value ) ? 'has-success' : 'has-danger'

    // Create textState object with all the fields
    const textState = Object.assign( {}, this.state.validate.textState, { [ e.target.name ]: fieldTextState})

    this.setState( { validate : { textState  } } )
};

另外,为每个输入设置特定的有效和无效

                         <AvInput valid
                            type="text"
                            name="title"
                            value={ this.state.activeItem.title }
                            //onChange={this.handleChange}
                            placeholder="Tool Name"
                            valid={ this.state.validate.textState.title === 'has-success' }
                            invalid={ this.state.validate.textState.title === 'has-danger' }
                            onChange={ ( e ) => {
                                this.validateText( e )
                                this.handleChange( e )
                            } }
                            required
                        />

                        <AvInput valid
                            type="text"
                            name="description"
                            value={ this.state.activeItem.description }
                            valid={ this.state.validate.textState.description === 'has-success' }
                            invalid={ this.state.validate.textState.description === 'has-danger' }
                            placeholder="Tool description"
                            onChange={ ( e ) => {
                                this.validateText( e )
                                this.handleChange( e )
                            } }
                            required
                        />

【讨论】:

  • 嘿,谢谢。好消息是,无效结果现在独立工作(如果一个失败,它不会将另一个标记为失败)。坏消息是,有效结果似乎根本不适用(它没有像以前那样得到漂亮的绿色轮廓和刻度线)。我会尽力调试它,但这可能会花我一天的时间:D
  • 好的,我认为这是因为您将 fieldTextState(因此是正则表达式的结果)分配给 e.name,它没有在任何地方定义。所以在变量窗口中我看到: textstate: description: "" title: "" undefined: "has-success"
  • 知道了(我想!)。我在 validateText 函数中添加了const { name} = e.target;,并更改了[e.name] to [name]。非常感谢,我整天都在努力让它工作:D
  • 事实证明我可以只做[e.target.name] 而不必担心 const。大功告成,再次感谢!
  • validateTexthandleChange 是否需要保护自己免受空 e 的影响?我猜onChange 触发它的原因很重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 2015-10-22
相关资源
最近更新 更多