如何避免立即验证使用formy-react构建的表单元素?

Rem*_*ure 6 javascript validation html5 reactjs

我正在使用formy-react来验证我的React表单,但我不希望验证在用户输入之前启动.只要该字段被标记为"必需",它似乎正在工作,但是当省略时,错误消息立即显示.

我做错了吗?

var React = require('React');
var Formsy = require('formsy-react');

var MyOwnInput = React.createClass({
    mixins: [Formsy.Mixin],

    changeValue: function (event) {
        this.setValue(event.currentTarget.value);
    },
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeValue} value={this.getValue()} placeholder={this.props.name}/>
                <span>{this.getErrorMessage()}</span>
            </div>
        );
    }
});

module.exports = React.createClass({
    render: function () {
        return (
            <Formsy.Form>
                <MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/>
                <MyOwnInput name="email2" validations="isEmail" validationError="This is not a valid email (no required attribute)"/>

                <button type="submit">Submit</button>
            </Formsy.Form>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

mar*_*cel 1

changeValue()将设置该值,该值反过来将验证该值以及表单的其余部分。您可以简单地尝试检查像这样的空字符串,以防止在开始时进行验证:

changeValue(event) {
    const newValue = event.currentTarget.value;
    if (newValue) this.setValue(newValue);
}
Run Code Online (Sandbox Code Playgroud)

如果它没有达到预期的效果,您可以添加一个状态来“阻止”验证,直到第一次更改为止。

getInitialState() {
    return {
        enableValidation: false
    }
}

changeValue(event) {
    const newValue = event;
    if (newValue && !this.state.enableValidation) this.setState({ enableValidation: true });
    if (newValue || this.state.enanbleValidation) this.setValue(newValue);
}
Run Code Online (Sandbox Code Playgroud)