Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Forms 表单验证:输出错误消息_Forms_Reactjs_Validation_Jsx - Fatal编程技术网

Forms 表单验证:输出错误消息

Forms 表单验证:输出错误消息,forms,reactjs,validation,jsx,Forms,Reactjs,Validation,Jsx,我使用React创建了以下表单并进行了验证: 数据应在输入时进行验证 提交前,应再次验证数据 所有数据所有字段均为必填字段,且数据有效 这个程序可以运行,但我有以下问题: 我使用onBlur监视数据检查,但当用户在第一个字段中输入无效数据时,第一个字段会显示错误消息(“仅字母”),第二个字段会显示错误消息(“此字段为必填字段”) 如何改进我的示例: 输入时-仅当用户触摸特定字段时,才会显示错误消息(“此字段为必填字段”或无效数据的特定消息) 如果按下“提交”按钮,则应在包含无效数据的所有字段

我使用React创建了以下表单并进行了验证:

  • 数据应在输入时进行验证
  • 提交前,应再次验证数据
  • 所有数据所有字段均为必填字段,且数据有效
这个程序可以运行,但我有以下问题:
我使用onBlur监视数据检查,但当用户在第一个字段中输入无效数据时,第一个字段会显示错误消息(“仅字母”),第二个字段会显示错误消息(“此字段为必填字段”)

如何改进我的示例:

  • 输入时-仅当用户触摸特定字段时,才会显示错误消息(“此字段为必填字段”或无效数据的特定消息)
  • 如果按下“提交”按钮,则应在包含无效数据的所有字段附近显示错误消息
  • 我的代码:

    const ErrorOutput=({error})=>{error}
    类FormItem扩展了React.Component{
    render(){
    返回(
    {this.props.label}
    {this.props.error&&}
    );
    }
    }
    类应用程序扩展了React.Component{
    建造师(道具){
    超级(道具)
    此.state={
    名字:'',
    电话号码:'',
    提交:错误,
    错误:{
    名字:'',
    电话号码:'',
    },
    无效:false,
    }
    }
    handleSubmit(e){
    e、 预防默认值()
    if(this.validate()){
    console.log('Error!')
    }否则{
    console.log('Success!')
    }
    }
    验证=()=>{
    const{firstName,telNo}=this.state
    常量错误={}
    设无效=假;
    如果(firstName==''){
    errors.firstName='firstName是必需的'
    无效=真;
    }如果(!firstName.match(/^[a-zA-Z]+$/),则为else{
    errors.firstName='仅限字母'
    无效=真;
    }  
    如果(电话号码==''){
    errors.telNo='Phone is required'
    无效=真;
    }如果(!telNo.match(/^[0-9]+$/)匹配,则为else{
    errors.telNo='仅限数字'
    无效=真;
    }
    这是我的国家({
    无效的
    错误,
    })
    返回无效;
    }
    render(){
    返回(
    this.setState({firstName:e.target.value}),
    onBlur:()=>this.validate(),
    }}error={this.state.errors.firstName}
    />
    this.setState({telNo:e.target.value}),
    onBlur:()=>this.validate(),
    }}error={this.state.errors.telNo}
    />
    提交
    )
    }
    }
    ReactDOM.render(
    ,
    document.getElementById('root'))
    )

    问题在于,一旦发生onBlur事件,valitade方法就会尝试验证所有字段。要解决此问题,可以将事件传递给validate方法,然后仅使用验证引发事件的字段

    event.target.name

    因此,您的验证方法将如下所示

    validate = e => {
      const { firstName, telNo } = this.state
      const errors = {}
      let invalid = false
      if (e && e.target.name == "firstName") {
        if (firstName === "") {
          errors.firstName = "first name is required"
          invalid = true
        } else if (!firstName.match(/^[a-zA-Z]+$/)) {
          errors.firstName = "Letters only"
          invalid = true
        }
      }
      if(e && e.target.name=="telNo"){
      if (telNo === "") {
        errors.telNo = "Phone is required"
        invalid = true
      } else if (!telNo.match(/^[0-9]+$/)) {
        errors.telNo = "Numbers only"
        invalid = true
      }
    }
      this.setState({
        invalid,
        errors
      })
    
      return invalid
    }
    
    你的表格看起来像

    <FormItem label='First name:' input={{
                type: 'text',
                name: 'firstName',
                value: this.state.firstName,
                onChange: e => this.setState({ firstName: e.target.value }),
                onBlur: (e) => this.validate(e),
              }} error = {this.state.errors.firstName}
            /> 
    
    this.setState({firstName:e.target.value}),
    onBlur:(e)=>this.validate(e),
    }}error={this.state.errors.firstName}
    /> 
    
    问题在于,一旦发生onBlur事件,valitade方法就会尝试验证所有字段。要解决此问题,可以将事件传递给validate方法,然后仅使用验证引发事件的字段

    event.target.name

    因此,您的验证方法将如下所示

    validate = e => {
      const { firstName, telNo } = this.state
      const errors = {}
      let invalid = false
      if (e && e.target.name == "firstName") {
        if (firstName === "") {
          errors.firstName = "first name is required"
          invalid = true
        } else if (!firstName.match(/^[a-zA-Z]+$/)) {
          errors.firstName = "Letters only"
          invalid = true
        }
      }
      if(e && e.target.name=="telNo"){
      if (telNo === "") {
        errors.telNo = "Phone is required"
        invalid = true
      } else if (!telNo.match(/^[0-9]+$/)) {
        errors.telNo = "Numbers only"
        invalid = true
      }
    }
      this.setState({
        invalid,
        errors
      })
    
      return invalid
    }
    
    你的表格看起来像

    <FormItem label='First name:' input={{
                type: 'text',
                name: 'firstName',
                value: this.state.firstName,
                onChange: e => this.setState({ firstName: e.target.value }),
                onBlur: (e) => this.validate(e),
              }} error = {this.state.errors.firstName}
            /> 
    
    this.setState({firstName:e.target.value}),
    onBlur:(e)=>this.validate(e),
    }}error={this.state.errors.firstName}
    /> 
    
    > p>您可能想考虑在应用程序中管理窗体状态。即使您不选择使用这个库,也可以查看在“代码>字段的包中定义的定义,以帮助确认在验证表单时应该考虑的事项。

    < P>您可能想考虑在应用程序中管理表单状态。即使您不选择使用此库,也值得一看在
    字段
    包装的输入上定义的,以帮助澄清在验证表单时应注意的事项。

    请从修改的代码中检查我的示例。我试着简化一下你的逻辑,让它更具可读性和通用性

    consterroroutput=({error})=>{error};
    常量FormItem=({标签,输入,错误})=>(
    {label}
    {错误&&}
    );
    类应用程序扩展了React.Component{
    状态={
    名字:“,
    电话号码:“,
    提交:错误,
    错误:{}
    };
    handleSubmit=()=>{
    const{firstName,telNo,errors}=this.state;
    const{firstnamererror,telNoError}=错误;
    const firstNameIsValid=firstName&!firstNameError;
    const telNoIsValid=telNo&!telNoError;
    firstNameIsValid&&telNoIsValid
    ?console.log(“成功!”)
    :console.log(“错误!”);
    };
    handleInput=事件=>{
    这是我的国家({
    [event.target.name]:event.target.value
    });
    };
    验证=()=>{
    const{firstName,telNo}=this.state;
    让错误={};
    //名称错误检查
    开关(真){
    凯斯!名字:
    errors.firstnamererror=“需要名字”;
    打破
    case!firstName.match(/^[a-zA-Z]+$/):
    errors.firstnamererror=“First name只能包含字母”;
    打破
    
    case firstName.length请从修改后的代码中检查我的示例。我已尝试稍微简化您的逻辑,使其更具可读性和通用性

    consterroroutput=({error})=>{error};
    常量FormItem=({标签,输入,错误})=>(
    {label}
    {错误&&}
    );
    类应用程序扩展了React.Component{
    状态={
    名字:“,
    电话号码:“,
    提交:错误,