React Js - Basic Form Validation
App.js:
import React, { useState } from 'react';
import './App.css'
function App()
{
const [name, setName]=useState("")
const [password, setPassword]=useState("")
const [userErr, setUserErr]=useState(false)
const [passErr, setPassErr]=useState(false)
function formHandle(e)
{
e.preventDefault();
if(name.length<3 || password.length<3)
{
console.warn("Enter Correct Values")
alert("Enter Correct Values")
}
else{
console.warn("All Good, Login Sucessfully")
alert("Login Sucessfully")
}
}
function userHandle(e)
{
let item=e.target.value;
if(item.length<3)
{
console.warn("Invalid")
setUserErr(true)
}
else{
setUserErr(false)
}
console.warn(e.target.value);
setName(item)
}
function passwordHandler(e)
{
let item=e.target.value;
if(item.length<3)
{
setPassErr(true)
}
else{
setPassErr(false)
}
setPassword(item)
}
return(
<div className='App'>
<form onSubmit={formHandle}>
<br/><br/>
<input type="text" placeholder="Enter Name" onChange={userHandle}/> {userErr?<span>Invalid User Name</span>:""}<br/><br/>
<input type="text" placeholder='Enter Password' onChange={passwordHandler}/>{passErr?<span>Invalid Password</span>:""} <br/><br/>
<button>Submit</button>
</form>
</div>
)
}
export default App;
Comments
Post a Comment