Home > Software design >  validate the input field and change it to another input field in ReactJS
validate the input field and change it to another input field in ReactJS

Time:01-04

I have been creating a React application which has a mobile number input field and after that I have added validation to mobile number input and it is working properly.

Now I want to change the input field to password without changing anything other than the form details by changing states i.e.

  1. Mobile number field to Password field
  2. Submit button to Login button.

Later on second form which is password I have a second onSubmit function to validate and route it to the next page.

Below, I have given the images and the code for your reference so that please help me out with the solving of my problem.

Here are the images: From This To this

This is the code for 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;

CodePudding user response:

You can render your JSX conditionally, since you have a state value isSubmit to check that first step has passed or not, you can render your forms like this:

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

or

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

CodePudding user response:

I think you want to keep base code and add another step or sth , you can create just one handleSubmit and for each input , you should pass that function the type , for example :

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

yourStep can be password or other in your state . and i think its better to check mode and in the handleSubmit to add specific validation or something else .

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