Last active
July 24, 2021 08:46
-
-
Save moaoa/7c4ded9af61b0dcaf90ccf60afb42b0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MIN_PASSWORD_LENGTH = 6; | |
const [data, setData] = React.useState({ | |
name: '', | |
email: '', | |
password: '', | |
confirmPassword:'' | |
}) | |
const errors = { | |
name: '', | |
email: '', | |
password: '', | |
confirmPassword:'' | |
}; | |
const handleChange = (field, event) => { | |
setData(prevState => { | |
return { | |
...prevState, | |
[field]: event.target.value | |
} | |
}) | |
} | |
const validate = (data) => { | |
Object.keys(data).forEach(key => { | |
if(!data[key]){ | |
errors[key] = key + ' field is required' | |
}else{ | |
errors[key] = '' | |
} | |
}) | |
// eslint-disable-next-line no-use-before-define | |
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
// if email is not avalide eamil | |
if(!errors.password && !re.test(data.email.toLowerCase())){ | |
errors.email = 'not a valid email' | |
} | |
if(data.password !== data.confirmPassword && !errors.password && !errors.confirmPassword){ | |
errors.confirmPassword = 'passwords must match' | |
} | |
if(!errors.password && String(data.password).length < MIN_PASSWORD_LENGTH){ | |
errors.password = 'psssword must be at least ' + MIN_PASSWORD_LENGTH + ' charecters .' | |
} | |
let pass = true; | |
Object.values(errors).forEach(value => { | |
// if there is any error | |
if(value){ | |
pass = false | |
} | |
}) | |
return pass; | |
} | |
const handleSubmit = () => { | |
const pass = validate(data); | |
if(pass){ | |
console.log('ok to send'); | |
}else{ | |
console.log(errors); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment