import React from
'react'
;
export
default
class App extends React.Component {
state = {
fields: {},
errors: {}
}
handleValidation = ()=>{
let fields =
this
.state.fields;
let errors = {};
let formIsValid =
true
;
if
(!fields[
"name"
]){
formIsValid =
false
;
errors[
"name"
] =
"Cannot be empty"
;
}
if
(
typeof
fields[
"name"
] !==
"undefined"
){
if
(!fields[
"name"
].match(/^[a-zA-Z]+$/)){
formIsValid =
false
;
errors[
"name"
] =
"Only letters"
;
}
}
if
(!fields[
"email"
]){
formIsValid =
false
;
errors[
"email"
] =
"Cannot be empty"
;
}
if
(
typeof
fields[
"email"
] !==
"undefined"
){
let lastAtPos = fields[
"email"
].lastIndexOf(
'@'
);
let lastDotPos = fields[
"email"
].lastIndexOf(
'.'
);
if
(!(lastAtPos < lastDotPos && lastAtPos > 0
&& fields[
"email"
].indexOf(
'@@'
) == -1 &&
lastDotPos > 2 && (fields[
"email"
].length - lastDotPos) > 2)) {
formIsValid =
false
;
errors[
"email"
] =
"Email is not valid"
;
}
}
this
.setState({errors: errors});
return
formIsValid;
}
handleSubmit = (e) =>{
e.preventDefault();
if
(
this
.handleValidation())
alert(
"form submitted successfully"
)
}
handleUpdate(field, e){
let fields =
this
.state.fields;
fields[field] = e.target.value;
this
.setState({fields});
}
render(){
return
(
<div style = {{margin:200}}>
<form onSubmit= {
this
.handleSubmit.bind(
this
)}>
<input type=
"text"
placeholder=
"Name"
onChange={
this
.handleUpdate.bind(
this
,
"name"
)}
value={
this
.state.fields[
"name"
]}/>
<span style={{color:
"red"
}}>
{
this
.state.errors[
"name"
]}</span>
<br/>
<input type=
"text"
placeholder=
"Email"
onChange={
this
.handleUpdate.bind(
this
,
"email"
)}
value={
this
.state.fields[
"email"
]}/>
<span style={{color:
"red"
}}>
{
this
.state.errors[
"email"
]}</span>
<br/>
<button type =
"submit"
>click</button>
</form>
</div>
)
}
}