I am struggling to comprehend this issue with using the addUser function to input user data only if the email goes through validation. All of this is initiated by clicking a button.
Below is the addUser function:
function addUser(username, email, callback) {
var xhr = new XMLHttpRequest();
var response;
var success = (!!Math.round(Math.random()));
if (!success){
response = JSON.stringify({
success: success,
error: "Oops, something went wrong!"
});
} else {
response = JSON.stringify({
success: success,
user: {
username: username,
email: email
}
});
}
xhr.open("POST", "/echo/json/");
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.send("json=" + response);
};
Here's my progress so far. I have attempted to invoke addUser, establish a success handler for the ajax response, enter in the email and username values. But none of it seems to be working.
function validation() {
var emailRegex = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;
var usernameInput = document.getElementById("userName").value;
var emailInput = document.getElementById("userEmail").value;
var emailError = document.getElementById('emailErr').textContent = "please enter a valid email address";
if(!emailRegex.test(emailInput)) {
emailError
}
}
function addUserClient() {
validation();
}
document.getElementById('addUserButton').addEventListener('click', addUserClient);