【问题标题】:validate the input field and change it to another input field in ReactJS验证输入字段并将其更改为 ReactJS 中的另一个输入字段
【发布时间】:2023-03-04 16:37:01
【问题描述】:

我一直在创建一个具有手机号码输入字段的 React 应用程序,之后我向手机号码输入添加了验证,它工作正常。

现在我想通过更改状态将输入字段更改为密码而不更改表单详细信息以外的任何内容,即

  1. 手机号码字段到密码字段
  2. 提交按钮到登录按钮。

稍后在第二个表单(即密码)上,我有第二个 onSubmit 函数来验证并将其路由到下一页。

下面,我提供了图片和代码供您参考,以便帮助我解决我的问题。

以下是图片:

这是 App.js 的代码:

    import React, { useState, useEffect } from 'react';
    import PhoneIcon from '@mui/icons-material/Phone';
    import LockIcon from '@mui/icons-material/Lock';
    import { NavLink, useNavigate } from 'react-router-dom';
    import "../../index.css";
    
    
    function Mobile () {
        
        
        const initialvalues = {number:"",password:""}
        const [formValues, setFormValues] = useState(initialvalues);
        const [formErrors, setFormErrors] = useState({});
        const [isSubmit, setIsSubmit] = useState(false);
    
    
        const handleChange = (e) =>{
            const{name,value} = e.target;
            setFormValues({...formValues, [name]:value});
        }
    
        const handleSubmit = (e) =>{
            e.preventDefault();
            setFormErrors(validate(formValues));
            setIsSubmit(true);
            console.log("hello")
        }
    const handleSubmits = (e) =>{
            e.preventDefault();
            const errors = validate(formValues);
          
            if (Object.keys(errors).length) {
              setFormErrors(errors);
            } else {
              navigate('afterlogin');
            }
          }
    
        useEffect(()=>{
            console.log(formErrors);
            if(Object.keys(formErrors).length ===0 && isSubmit){
                console.log(formValues);
            }
        },[formErrors])
    
        const validate = (values) =>{
            const errors = {}
            
            const regexn = /^(\+91[-\s]?)?[0]?(91)?[789]\d{9}$/;
            
            
            const regexp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{4,12}$/;
    
            
            if(!values.number){
                errors.number = "Mobile Number is required";
            }else if(!regexn.test(values.number)){
                errors.number = "Please enter a valid mobile number"
            }else if(values.number.length > 10){
                errors.number = "number must be only 10 digits"
            }
    
            return errors;
            
        };
        
            return (
                <div className="container" 
                        style={{textAlign:'center'}}>
                    
                    <div style={{justifyContent:'space-between'}}>
            {/*from this*/}
                    <form onSubmit={handleSubmit}>
                        <div >
                        
                        <div>
                            {/*style={{position:"relative",top:"",
                                            left:"6rem",cursor:"text",color:"blue"}} */}
                            <label style={{position:"relative", top:"8px",right:"5px"}}><PhoneIcon/></label>
    
                            <input className='input_field' type="number" name="number" placeholder=''
                                    autoComplete='off'
                                    value={formValues.number}
                                    onChange={handleChange}
                                    style={{width:"180px",height:"35px"}}
                            />
                            <label className='input_label'>Mobile Number</label>
    
                            <p style={{color:"red"}} >{formErrors.number}</p>
                        </div>
                            <button className='btn-primary'
                                        style={{width:"210px",height:"30px",fontSize:"15px",
                                                marginLeft:"10px",
                                                backgroundColor:"skyblue"
                                                }}>
                                                Submit</button>
                        </div>
{/*to this */}
                    </form>
                                        <form onSubmit={handleSubmits}>
                        <div >
                        
                        
                        <div>
              <form onSubmit={handleSubmits}> <div> <label style={{position:"relative", top:"8px",right:"5px"}} ><LockIcon/></label> <input className='input_field' type="password" name='password' placeholder='' value={formValues.password} onChange={handleChange} style={{width:"180px",height:"35px"}} /> <label className='input_label'>Password</label> <p style={{color:"red"}}>{formErrors.password}</p> </div> </form>
                            <button className='btn-primary'
                                        style={{width:"210px",height:"30px",fontSize:"15px",
                                                marginLeft:"10px",
                                                backgroundColor:"skyblue"
                                                }}>
                                                Submit</button>
                        </div>
                    </form>
    
                    </div>
                </div>
            )
        }
    
    export default Mobile;

【问题讨论】:

    标签: reactjs forms validation material-ui


    【解决方案1】:

    您可以有条件地渲染您的JSX,因为您有一个状态值isSubmit 来检查第一步是否通过,您可以像这样渲染您的表单:

     { !isSubmit && <form onSubmit={handleSubmit}>mobile form</form> } 
     { isSubmit && <form onSubmit={handleSubmits}>password form</form> }
    

     { !isSubmit ?
       <form onSubmit={handleSubmit}>mobile form</form> : 
       <form onSubmit={handleSubmits}>password form</form>
     }
    

    【讨论】:

    • 这样我可以默认显示移动表单,然后通过验证后会通过隐藏移动表单来显示密码表单?
    • 是的,但是你应该更新你的isSubmit状态,如果移动表单是有效的,例如在handleSubmit你可以这样做:const errors = validate(formValues); if(!errors.number){ setIsSubmit(true) } else { setFormErrors(errors) }
    • 嘿,非常感谢@Saeed Shamloo 的建议。这是一个很大的帮助,我通过一些小的调整成功地完成了我真正想要的。
    • 不客气。
    【解决方案2】:

    我认为您想保留基本代码并添加另一个步骤或某事,您可以只创建一个 handleSubmit 并且对于每个输入,您应该向该函数传递类型,例如:

    <form onSubmit={(e) => handleSubmit(e,yourStep)}
    ...
    </form>
    

    yourStep 可以是您所在州的密码或其他密码。 我认为最好检查模式并在 handleSubmit 中添加特定的验证或其他内容。

    const handleSubmit = (e,type) => {
    if(type === "password"){
       handlePassword() /// Or something
    }
    // doSomthing general 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2021-11-22
      • 2012-07-24
      相关资源
      最近更新 更多