add validation for username and email on signup

This commit is contained in:
Sorrel Bri 2020-01-17 22:56:09 -08:00
parent bd1c90da99
commit 22b6dc443a
3 changed files with 51 additions and 27 deletions

View file

@ -8,30 +8,73 @@ const Signup = (props) => {
const [ email, setEmail ] = useState('');
const [ password, setPassword ] = useState('');
const [ confirmPassword, setConfirmPassword ] = useState('');
const minimumPasswordLength = 8;
const errorDispatchAction = {
type: 'ERR',
message: 'AUTH_ERROR'
}
const handleSubmit = async e => {
e.preventDefault();
const validateSignupForm = (next) => {
if (password !== confirmPassword) {
return props.dispatch({
type: 'ERR',
message: 'AUTH_ERROR',
...errorDispatchAction,
body: { authError: 'Password fields must be the same'}
})
}
if (password.length < 8) {
return props.dispatch({
...errorDispatchAction,
body: { authError: 'Password must be at least 8 characters'}
})
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return props.dispatch({
...errorDispatchAction,
body: { authError: 'Please enter a valid email'}
})
}
if (!/^[\w\d_.-]+$/.test(username)) {
return props.dispatch({
...errorDispatchAction,
body: { authError: "Username can only contain letters, numbers, '_', '.', or '-'"}
})
}
return next();
}
const postSignupForm = async () => {
const signupResponse = await authServices.signupService({
username,
email,
password,
confirmPassword
})
const parsedResponse = JSON.parse(signupResponse)
if (parsedResponse.errors) {
const authError = parsedResponse.errors[0].auth
return props.dispatch({
...errorDispatchAction,
body: { authError }
})
}
return props.dispatch({
type: 'AUTH',
message: 'SIGNUP',
body: signupResponse
body: parsedResponse
})
}
const handleSubmit = async e => {
e.preventDefault();
validateSignupForm(postSignupForm);
}
const formError = errors => {
if(!errors) return <></>;

View file

@ -25,25 +25,6 @@ function loginReducer(state: state, action: action): state {
}
function signupReducer(state: state, action: action): state {
const signupResponse = action.body;
let error;
if (signupResponse.response) {
error = signupResponse.response.data.errors;
}
let responseUser;
if (signupResponse.data) {
responseUser = {...signupResponse.data}
}
if (error) {
const errors = error.reduce((errorObject, error) => errorObject[Object.keys(error)[0] = error])
return {...state, errors };
}
if (responseUser) {
return {...state, user: responseUser };
}
return {...state, errors: {requestError: 'something went wrong'}};
const newUser = action.body;
return {...state, user: newUser };
}

View file

@ -21,7 +21,7 @@ const signupService = async (formData) => {
headers: headers
})
.then(res => {
return res;
return res.text();
}).catch(err => {
return err;
});