I’m using an email validation plugin that works fine, but I need help with controlling the submit button. I want the submit button to be disabled when the email is invalid and enabled when it’s valid. Here’s my current setup:
$('#userEmail').email_checker({
apiKey: 'your-key-here',
onCheck: check_in_progress,
onValid: check_success,
onInvalid: check_failed,
});
// checking state
function check_in_progress() {
$('#result').html("<img src='spinner.gif' width='20'/>");
}
// valid email
function check_success(response) {
$('#result').html(build_message(response['valid'], response['suggestion']));
}
// error occurred
function check_failed(msg) {
$('#result').html(msg);
}
// create message
function build_message(valid, suggestion) {
if (suggestion) {
return '<span class="hint">Maybe you meant <strong>' + suggestion + '</strong>?</span>';
} else if (valid) {
return '';
} else {
return '<span class="error-msg">Email format is wrong.</span>';
}
}
I know I need to use $("#submitBtn").prop('disabled', true); but I’m not sure where to place this code in my validation functions. Can someone help me figure out the right spots to enable and disable the button?
you should disable the button in check_in_progress and check_failed, then enable it in check_success. something like $("#submitBtn").prop('disabled', false); when the email is valid should do the trick!
Your validation has different outcomes, so you need to handle the button state in several spots. Disable it in check_in_progress while validation runs. In check_success, don’t just assume success means the email’s valid - check response['valid'] directly. Your build_message function already handles cases where the response isn’t valid even in the success callback. I’d also disable the button when the page loads and whenever input changes to prevent submitting unchecked emails. Here’s what trips people up: the success callback just means the API call worked, not that the email passed validation.
Hit this same problem last month - there’s a detail everyone else missed. Your build_message function returns different stuff depending on validation state, so use that same logic for the button. In check_success, check the same conditions as build_message - if there’s a suggestion or invalid email, keep the button disabled. Only enable it when valid is true and no suggestion exists. Don’t forget to disable the button on page load and whenever the email input changes, or users can submit before validation runs. Bottom line: your button logic needs to match your message display logic exactly since they both use the same response data.