SOLVED

How do I get a form to display an error message in real time

Go to solution
Troy_Larson
Level 3

How do I get a form to display an error message in real time

Hey guys, 

 

So big thanks to the people that put the JS out that to block "free" email addresses from form submissions. My question is, how do I get it so that the alert that pops up displays once a user moves on to the next field. Right now it will display when they hit the submit button. 


Anyone know what needs to be done? 

 

For reference, here's the JS I'm using: 

(function (){
// Please include the email domains you would like to block in this list
var invalidDomains = ["@gmail.","@yahoo.","@hotmail.","@live.","@aol.","@outlook."];
MktoForms2.whenReady(function (form){
form.onValidate(function(){
var email = form.vals().Email;
if(email){
if(!isEmailGood(email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage("Must be Business email.", emailElem);
}else{
form.submitable(true);
}
}
});
}); function isEmailGood(email) {
for(var i=0; i < invalidDomains.length; i++) {
var domain = invalidDomains[i];
if (email.indexOf(domain) != -1) {
return false;
}
}
return true;
}
})();
1 ACCEPTED SOLUTION

Accepted Solutions
SanfordWhiteman
Level 10 - Community Moderator

Re: How do I get a form to display an error message in real time

To start with, that code (though often copied-and-pasted) is broken. It doesn't properly parse the domains case-insensitively so it will allow mailbox@GmAiL.com.

 

It also assumes certain things I wouldn't, like that mailbox@live.example.com is necessarily a Microsoft address. But I'll let that go.

 

Now, acknowledging that you need better validation logic (provided as part of the code below) it's easy to trigger revalidation on the blur event fired by the Email input.

/*
 * @author Sanford Whiteman
 * @version v1.0 2020-10-22
 * @copyright © 2020 Sanford Whiteman
 * @license Hippocratic 2.1: This license must appear with all reproductions of this software.
 *
 *
 *
 */
(function () {
   // Please include the email domains you would like to block in this list
   var invalidDomains = [
      "@gmail.",
      "@yahoo.",
      "@hotmail.",
      "@live.",
      "@aol.",
      "@outlook."
   ];
   var interestingEmailField = "Email";

   MktoForms2.whenReady(function (mktoForm) {
      let formEl = mktoForm.getFormElem()[0],
         emailEl = formEl.querySelector("[name='" + interestingEmailField + "']");

      mktoForm.onValidate(extendedEmailValidation);
      emailEl.addEventListener("blur", extendedEmailValidation);

      function extendedEmailValidation(nativeValid) {
         if (nativeValid === false) return;

         let currentValues = mktoForm.getValues(),
            email = currentValues[interestingEmailField];

         if (email) {
            if (isInvalidDomain(email)) {
               emailEl.classList.add("customInvalid");
               emailEl.setAttribute("aria-invalid","true");
               mktoForm.submittable(false);
               mktoForm.showErrorMessage("Must be Business email.", MktoForms2.$(emailEl) );
            } else {
               emailEl.classList.remove("customInvalid");
               emailEl.setAttribute("aria-invalid","false");
               mktoForm.submittable(true);
            }
         }
      }

      function isInvalidDomain(email) {
         return invalidDomains.some(function(domainPrefix){
            return new RegExp(domainPrefix.replace(".","[.]")+"[a-z.-]+$","i").test(email);
         });
      }
      
   });
})();

 

But you're still not out of the woods, because there's a bug in the forms library that causes the red-error-message-and-arrow widget to show quickly and then disappear — if the validation was fired outside of the normal submit process.

 

To keep the error message shown, you need to hack the CSS a bit. And it still isn't pretty.

.mktoForm [name="Email"].customInvalid ~ .mktoError {
    display: block !important;
    opacity: 1 !important;
}

 

View solution in original post

1 REPLY 1
SanfordWhiteman
Level 10 - Community Moderator

Re: How do I get a form to display an error message in real time

To start with, that code (though often copied-and-pasted) is broken. It doesn't properly parse the domains case-insensitively so it will allow mailbox@GmAiL.com.

 

It also assumes certain things I wouldn't, like that mailbox@live.example.com is necessarily a Microsoft address. But I'll let that go.

 

Now, acknowledging that you need better validation logic (provided as part of the code below) it's easy to trigger revalidation on the blur event fired by the Email input.

/*
 * @author Sanford Whiteman
 * @version v1.0 2020-10-22
 * @copyright © 2020 Sanford Whiteman
 * @license Hippocratic 2.1: This license must appear with all reproductions of this software.
 *
 *
 *
 */
(function () {
   // Please include the email domains you would like to block in this list
   var invalidDomains = [
      "@gmail.",
      "@yahoo.",
      "@hotmail.",
      "@live.",
      "@aol.",
      "@outlook."
   ];
   var interestingEmailField = "Email";

   MktoForms2.whenReady(function (mktoForm) {
      let formEl = mktoForm.getFormElem()[0],
         emailEl = formEl.querySelector("[name='" + interestingEmailField + "']");

      mktoForm.onValidate(extendedEmailValidation);
      emailEl.addEventListener("blur", extendedEmailValidation);

      function extendedEmailValidation(nativeValid) {
         if (nativeValid === false) return;

         let currentValues = mktoForm.getValues(),
            email = currentValues[interestingEmailField];

         if (email) {
            if (isInvalidDomain(email)) {
               emailEl.classList.add("customInvalid");
               emailEl.setAttribute("aria-invalid","true");
               mktoForm.submittable(false);
               mktoForm.showErrorMessage("Must be Business email.", MktoForms2.$(emailEl) );
            } else {
               emailEl.classList.remove("customInvalid");
               emailEl.setAttribute("aria-invalid","false");
               mktoForm.submittable(true);
            }
         }
      }

      function isInvalidDomain(email) {
         return invalidDomains.some(function(domainPrefix){
            return new RegExp(domainPrefix.replace(".","[.]")+"[a-z.-]+$","i").test(email);
         });
      }
      
   });
})();

 

But you're still not out of the woods, because there's a bug in the forms library that causes the red-error-message-and-arrow widget to show quickly and then disappear — if the validation was fired outside of the normal submit process.

 

To keep the error message shown, you need to hack the CSS a bit. And it still isn't pretty.

.mktoForm [name="Email"].customInvalid ~ .mktoError {
    display: block !important;
    opacity: 1 !important;
}