forminreactlamadev
Form.js
import React, { useState } from 'react'
// import {Input} from './Input'
import FormInput from './FormInput';
import './style/style.css'
export default function Form() {
const initialstate={
username:'',
userpass:''
}
const [state,setState]=useState('');
const Input=[
{
id:1,
name:'username',
type:'text',
placeholder:'username',
label:'username',
required:true,
errorMessage:'please fillname at least 3 character',
pattern:"^[a-zA-Z]{3,5}$"
}
,{
id:2,
name:'userpass',
type:'password',
placeholder:'userpass',
label:'userpass',
required:true,
errorMessage:'please fillpassword',
pattern:"^[a-zA-Z0-9]{3,5}$"
},
{
id:3,
name:'confirmuserpassword',
type:'password',
placeholder:'confirmuserpass',
label:'confirmuserpass',
required:true,
errorMessage:"password doesn't match",
pattern:state.userpass
},
{
id:4,
type:'submit',
label:'submit'
}]
console.log(...Input);//opreator for object destructuring...
//handel onchange...
const onChange=(e)=>{
console.log(e.target);
setState({...state,[e.target.name]:e.target.value})
}
const handelSubmit=(e)=>{
e.preventDefault();
}
return (
<div>
<form onSubmit={handelSubmit}>
{Input.map((input)=>(
<FormInput key={input.id} {...input} value={state[input.value]} onChange={onChange}
/>
)
)}
</form>
</div>
)
}
FormInput.js
import React,{useState} from 'react'
export default function FormInput(props) {
console.log(props);
const [focususer,setUserfocus]=useState(false);
const {label,onChange,id,errorMessage,...inputprops}=props;//destruring...
const handelFocus=(e)=>{
setUserfocus(true);
}
return (
<div>
{/* focususer should be true */}
<input {...inputprops} onChange={onChange} onBlur={handelFocus} focused={focususer.toString()}
onFocus={()=>{
inputprops.name==="confirmuserpassword" && setUserfocus(true)
}}
/>
<span >{errorMessage}</span>
</div>
)
}
style.css
span{
color:red;
display:none;
}
/*if input is invalid then show span*/
/* input:invalid ~ span{
border:red;
display: block;
} */
/*if focused is true and input is invalid then show span*/
input:invalid[focused="true"] ~ span{
border:red;
display: block;
}
input:invalid[focused="true"] {
border:1px solid red;
}
Comments
Post a Comment