Form_reactjs
import React,{useState} from 'react';
export default function Form() {
const initalvalues={username:'',userpass:''}
const [state, setState] =
useState(initalvalues);
const [formError,setFormErrors]=useState({})
const username=state.username;
const userpass=state.userpass;
const handlechange=(e)=>{
console.log(e.target);
const {name,value}=e.target;
setState({...state,[name]:value})
}
const handlesubmit=(e)=>{
e.preventDefault();
Validate(state);
}
const Validate=(state)=>{
//console.log("username"+state.username);
//console.log("password"+state.userpass);
const errors={};
const regexusername=/^[A-Z a-z\\s]+$/;
const passw= /^[A-Za-z]\w{7,14}$/;
if(!state.username){
// alert("please fill username");
errors.username="please fill username";
}
if(!regexusername.test(state.username)){
errors.username="username must be character";
}
if(!state.userpass){
//alert("please fill password");
errors.userpass="please fill password"
}
if(!passw.test(state.userpass)){
errors.userpass="password must
be min 7 to max 14";
}
setFormErrors(errors);
}
return <div>
<form action="" onSubmit={handlesubmit}>
<label htmlFor="username">Name</label>
<input type="text" name="username"
value={username}
onChange={handlechange}
/>
<span>{formError.username}</span>
<br />
<label htmlFor="password">Password</label>
<input type="password" name="userpass"
value={userpass}
onChange={handlechange} />
<span>{formError.userpass}</span>
<br />
<input type="submit" value="login" />
</form>
</div>;
}
Comments
Post a Comment