So I have 2 functions, one is a async function that is basically a HTTP Post Request, the other one is a form validation. I want the POST Request function to trigger only if the form validation function returns true. The form validation looks like this:
regForm.addEventListener('submit', function(event){
if (checkInputs()) {
// trigger post request function
}
})
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
}
But this doesn't seem to work, it doesn't trigger the POST Request function.
inside function checkInputs(), create a variable let check = true, assign false to this variable in every if statement:
if (usernameValue === '') {
setError()
check = false;
}
return check; at the end of function.
It triggers, because you don't return anything from the checkInputs function.
You need to return boolean /true or false/.
Something like:
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
let check = true;
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
return check;
}
Related
I have a registration form. When I click the Register button all TextInputs are validated and for each field I call a function in which I call e.g. this.setState({usernameError: 'This field is required'}).
So for each text field I have a function to set the error state for this field. After I press the Register button I want to validate all fields and then return the function if there is any field error in the state (The user may not register if all fields have not been filled in correctly). The problem is: Because setState is asynchronous, it is not guaranteed that all field errors are already correctly set when I check them.
2 important annotations:
I know the second parameter (the callback) of setState, but I can't execute the condition (which checks the field errors in the state) in this callback because the setState calls are located in their own function
They are located in their own function because I want to reuse the logic (I also call the validate<FieldName> functions in other places, e.g. when the onChangeText event occurs)
So my question is: How to make sure the state is already updated when checking its values without giving up my reusable "validator functions"?
Some code to make it clearer:
state = { usernameError: '', firstNameError: '', lastNameError: '' };
setUsernameError = () => { // This function is also called elsewhere than in handlePressRegister
const { username } = this.state;
if (username === '')
this.setState({ usernameError: 'Required field' });
else if (username.length < 2)
this.setState({ usernameError: 'Minimum 2 characters' });
else
this.setState({ usernameError: undefined });
}
setFirstNameError = () => { // This function is also called elsewhere than in handlePressRegister
...shortened for brevity...
}
setLastNameError = () => { // This function is also called elsewhere than in handlePressRegister
...shortened for brevity...
}
handlePressRegister = () => {
const { usernameError, firstNameError, lastNameError } = this.state;
this.setUsernameError();
this.setFirstNameError();
this.setLastNameError();
if (usernameError || firstNameError || lastNameError) // The errors may not be set in the state yet
return;
I hope you understand my question correctly.
I would handle this by having the various set[X]Error functions return their new value. For example:
setUsernameError = () => {
const { username } = this.state;
let error = undefined;
if (username === '')
error = 'Required field';
else if (username.length < 2)
error = 'Minimum 2 characters';
this.setState({ usernameError: error });
return error;
}
handlePressRegister = () => {
const usernameError = this.setUsernameError();
const firstNameError = this.setFirstNameError();
const lastNameError = this.setLastNameError();
if (usernameError || firstNameError || lastNameError) {
return;
}
// ...
}
If you promisify setState, you could return it from each validator call and call Promise.all on it:
setUsernameError = () => { // This function is also called elsewhere than in handlePressRegister
const { username } = this.state;
if (username === '')
return setStatePromisified({ usernameError: 'Required field' });
// ...
Promise.all([
this.setUsernameError(),
this.setFirstNameError(),
this.setLastNameError(),
])
.then(() => {
// state will be updated now
const { usernameError, firstNameError, lastNameError } = this.state;
if (usernameError || firstNameError || lastNameError) {
return;
}
// submit?
});
Another option would be to add another property into state, say, validating, that gets set when the register button is pressed. The next render, detect its change in a componentDidUpdate, reset validating, and continue with the logic as needed (submit the form if no errors?).
I've been working on this for two days now and I still can't figure out why my elements are sometimes either returning null or other times returning undefined but never returning the properties themselves. I've set their ID's in the respective HTML file and I still get null or undefined.
I've tried using setTimeout() but that didn't work because I was redirecting to a new page. I tried using an event listener on the document with DOMContentLoaded. I've even tried window.onload
var userEmailDisplay;
var newPaswordInput;
var confNewPaswordInput;
var submitNewPasswordBtn;
const urlParams = getAllUrlParams(window.location.href);
const actionCode = urlParams.oobCode;
window.onload = () => {
var doc = document;
switch (urlParams.mode) {
case 'resetPassword':
handleResetPassword(actionCode);
break;
case 'recoverEmail':
handleRecoverEmail(actionCode);
break;
case 'verifyEmail':
handleVerifyEmail(actionCode);
break;
}
// get new password elements
/* if (window.location.href.indexOf("new-password") > -1) {
userEmailDisplay = doc.getElementById('account-email-new-pswd');
newPaswordInput = doc.getElementById('new-password-input');
confNewPaswordInput = doc.getElementById('conf-new-password-input');
submitNewPasswordBtn = doc.getElementById('update-pswd-sub-btn');
} */
}
function handleResetPassword(actionCode) {
// Verify the password reset code is valid.
auth.verifyPasswordResetCode(actionCode).then(function (email) {
window.location.href = "https://couch-potato-880f0.firebaseapp.com/email/new-password.html";
console.log("code verified");
confirmThePswdReset(actionCode, email);
}).catch(function (error) {
console.error(error);
});
}
function confirmThePswdReset(actionCode, email) {
window.onload = () => {
userEmailDisplay = document.getElementById('account-email-new-pswd');
newPaswordInput = document.getElementById('new-password-input');
confNewPaswordInput = document.getElementById('conf-new-password-input');
submitNewPasswordBtn = document.getElementById('update-pswd-sub-btn');
console.log(submitNewPasswordBtn + ' + ' + userEmailDisplay);
if (submitNewPasswordBtn && userEmailDisplay) {
submitNewPasswordBtn.addEventListener('click', function (e) {
e.preventDefault();
const accountEmail = email;
console.log('submit btn clicked');
const newPassword = newPaswordInput.value;
const confNewPasswordValue = confNewPaswordInput.value;
userEmailDisplay.innerHTML = `Email: ${accountEmail}`;
if (newPassword != confNewPasswordValue) {
alert('The new passwords must match!');
return;
}
console.log(newPassword);
// Save the new password.
auth.confirmPasswordReset(actionCode, newPassword).then(function (resp) {
// Password reset has been confirmed and new password updated.
alert("All good");
window.location.replace('/email/confirm-password-reset.html');
}).catch(function (error) {
console.error(error);
});
});
}
}
}
I expect when I click the submit button on the new password page, there's the alert box to pop up saying that everything is good and the password has been reset but that never happens. The code only goes up to the if-statement that checks if submitNewPasswordBtn and userEmailDisplay exist and are not null. I know that because I never get an output log saying that the submit button was clicked. Sometimes I never even get the output checking that submitNewPasswordBtn and userEmailDisplay exist and have values.
I have been looking at this code for too long and just can't see what I am missing. The error states that there is a syntax error on the very last line, I have checked all of my braces but cannot seem to find it. Can anyone help me to find it?
window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');
// if the form is found...
if (form) {
// obtain error fields
var aname = $('accountname');
var anumber = $('accountnumber');
var cname = $('cardname');
var cnumber = $('cardnumber');
var security = $('securitycode');
var zip = $('zipcode');
// Set the default status
var isValid = true;
// input error function for the error messages
var addError = function (field, msg) {
field.addClass('error'); // Add error class to field
var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
error.set('text', msg); // error text msg
error.inject(field, 'after'); // Insert error message after field
};
// detach error function used to delete any error messages and remove the error class
var removeError = function (field) {
field.removeClass('error'); // Remove error class from form fields
var error = field.getParent().getElement('span'); // find any existing error messages
// destroy if error message
if (error) {
error.destroy();
}
};
// insert submit form event
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
form.addEvent('submit', function (e) {
// Test name length
if (anumber.get('value').length === 0) {
isValid = false;
addError(anumber, accountnumberError);
} else {
isValid = true;
removeError(accountnumber);
}
form.addEvent('submit', function (e) {
// Test name length
if (cname.get('value').length === 0) {
isValid = false;
addError(cname, nameError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (cnumber.get('value').length === 0) {
isValid = false;
addError(cnumber, numberError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (securitycode.get('value').length === 0) {
isValid = false;
addError(securitycode, securityError);
} else {
isValid = true;
removeError(securitycode);
}
form.addEvent('submit', function (e) {
// Test name length
if (zipcode.get('value').length === 0) {
isValid = false;
addError(zipcode, zipError);
} else {
isValid = true;
removeError(zipcode);
}
// If form invalid then stop event happening
if (!isValid) {
e.stop();
}
});
}
});
You're missing the end curly brace and closing paranthesis for each form.addEvent('submit', function (e) {. Also, you could combine them into a single handler. Using a beautifier helps you easily find if these types of syntax errors.
Example for one of them
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
}); // <- you don't have that
On a side note, your var aname = $('accountname'); (and subsequent lines) look wrong. You probably mean to select it by id; use $('#accountname'). And I'm not aware of any addEvent function. I'm assuming you're using some other library, but for reference with jQuery you should use .on(event, handler)
I'm quite new to JavaScript and I'm having an issue with a contact form.
I have 2 if statements and I return false at the end of the second one, but when I execute this, with both fields empty, its happy, and my error msgs pop up, and the email doesn't send. but if I only enter information in the second input field, it thinks the form is filled out, even with the first field empty.
How do I stop the email from sending if either one of the if statements is false?
My code
function checkForm(){
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
return false;
}
else{
return true;
}
}
Keep track of the state and have one return statement at the end.
function checkForm(){
var isValid = true;
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
isValid = false;
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
isValid = false;
}
return isValid;
}
And looking at your code, I am hoping you have
var addressErrorMsg = document.getElementById("SomeId");
above your code and you are not just using the id to reference the element.
function checkForm(){
var validate = true;
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
validate = false;
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
validate = false;
}
return validate;
}
I am using this to detect errors on my form...
var error = false;
if (val === '') {
error = true;
}
if (error = true) {
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
Simple really but not working, am I missing something stupid? variable error is default false.
If an error is found it is true.
If error is found to be true it prevents the form being submitted?
var error = false;
if (val === '') { // <<< This checks type first, then value
// An empty '' variable is not type-equivalent
// to a (boolean) false value
error = true;
}
if (error = true) { // <<< You're setting a variable here, which means
// means that you're testing if the variable
// assignment itself is successful, you'll get
// a true result in most cases, and except with
// things like while loops, you shouldn't use this
// form.
// Maybe you want == (falsy)? Or === (type-checked)?
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
You should do the checking in the submit event handler:
$('#joinForm').submit(function(event) {
var error = false;
if (val === '') {
error = true;
}
if (error) {
event.preventDefault();
}
});