We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 7976
    • 36 Posts
    Heya! I am trying to get a general validation warning on top of my form (as used in eForm), with this I mean the following example:

    Some errors were detected in your form:
    The following required field(s) are missing: Name, Company, Phone number

    Does anyone have an idea or direction on how I can get this done?

    p.s. webstandards: please no empty labels, paragraph or spans
    p.s.2 I am also aware of [[fi.error.FIELDNAME]] but it aint an option (designwise!)
    [[!FormIt? 
    &hooks=`spam,email,redirect` 
    &emailTpl=`emailContact`
    &emailSubject=`Contactformulier masked.nl`
    &emailTo=`[email protected]` 
    &redirectTo=`45`
    &validate=`naam:required,email:email,bedrijf:required,bericht:required`
    ]]
    <div class="wrapper contact main">
    [[+fi.error.error_message]]
    <form id="formContact" name="formContact" method="post" action="[[~[[*id]]]]"> 
    	<input type="hidden" name="nospam:blank" value="" /> 
    	<div class="input naam extend [[!+fi.error.naam:notempty=`error`]]">
    		<label for="naam">Naam:</label>
    		<input type="text" name="naam" id="naam" value="[[+fi.naam]]" />
    	</div>
    	<div class="input email extend [[!+fi.error.email:notempty=`error`]]">
    		<label for="email">E-mailadres:</label>
    		<input type="text" name="email" id="email" value="[[+fi.email]]" />
    	</div>
    	<div class="input bedrijf extend [[!+fi.error.bedrijf:notempty=`error`]]">
    		<label for="bedrijf">Bedrijf:</label>
    		<input type="text" name="bedrijf" id="bedrijf" value="[[+fi.bedrijf]]" />
    	</div>
    	<div class="input bericht extend [[!+fi.error.bericht:notempty=`error`]]">
    		<label for="bericht">Bericht:</label>
    		<textarea name="bericht" id="bericht">[[+fi.bericht]]</textarea>
    	</div>
    	<input type="submit" name="submit" id="submit" value="Submit"  />
    </form>
    </div>
    
      Jack of all Trades and Proud Honda Zoomer owner. Also available on twitter.
      • 7976
      • 36 Posts
      I found it! I solved the problem with a custom validator.

      Default FormIt:
      [[!FormIt? 
        &hooks=`spam,email,redirect` 
        &emailTpl=`emailContact`
        &emailSubject=`Contactform`
        &emailTo=`[email protected]`
        &emailHtml=`true`
        &redirectTo=`41`
        &customValidators=`FormItValidator`
        &validate=`
          naam:required:FormItValidator:stripTags,
          email:email:FormItValidator:stripTags,
          bedrijf:required:FormItValidator:stripTags,
          bericht:required:FormItValidator:stripTags`
      ]]
      <div class="wrapper contact main">
      [[!FormItValidator? &checkValidation=`true` &Htmltag=`p`]]
      <form id="formContact" name="formContact" method="post" action="[[~[[*id]]]]"> 
          <input type="hidden" name="nospam:blank" value="" /> 
          <div class="input naam extend [[!+fi.error.naam:notempty=`error`]]">
              <label for="naam">Naam:</label>
              <input type="text" name="naam" id="naam" value="[[+fi.naam]]" />
          </div>
          <div class="input email extend [[!+fi.error.email:notempty=`error`]]">
              <label for="email">E-mailadres:</label>
              <input type="text" name="email" id="email" value="[[+fi.email]]" />
          </div>
          <div class="input bedrijf extend [[!+fi.error.bedrijf:notempty=`error`]]">
              <label for="bedrijf">Bedrijf:</label>
              <input type="text" name="bedrijf" id="bedrijf" value="[[+fi.bedrijf]]" />
          </div>
          <div class="input bericht extend [[!+fi.error.bericht:notempty=`error`]]">
              <label for="bericht">Bericht:</label>
              <textarea name="bericht" id="bericht">[[+fi.bericht]]</textarea>
          </div>
          <input type="submit" name="submit" id="submit" value="Submit" class="button" />
      </form>
      </div>


      Snippet ’FormItValidator’
      <?php
      if($checkValidation=='true') { //Echo error
      
        if(!$modx->FItmpString) { //No errors show default intro text
         echo '<'.$Htmltag.' class="contactUs">'.$modx->lexicon('formit.formIntro').'.</'.$Htmltag.'>';
      
        } else { // Errors, show default error message
          $modx->FItmpString = substr($modx->FItmpString,0,-2);
          echo '<'.$Htmltag.' class="error">'.$modx->lexicon('formit.formErrors').$modx->lexicon('formit.formErrorsMissing').$modx->FItmpString.'.</'.$Htmltag.'>';
          unset($modx->FItmpString);
        }
        return;
      
      } else { //check POSTed vars
      
        if ($validator->errors[$key]) {
          if($modx->FItmpString == "" OR !$modx->FItmpString) {
              $modx->FItmpString = $key.', ';
          } else {
              $modx->FItmpString .= $key.', ';
          }
          return false;
        } else {
          return true;
        }
      }


      Lexicons
      formit.formErrors = <strong>Some errors were detected in your form</strong><br/>
      formit.formErrorsMissing = The following required field(s) are missing: 
      formit.formIntro = Your personal intro message, use below bla bla bla
      


      If you got a better solution I would love to hear it!
        Jack of all Trades and Proud Honda Zoomer owner. Also available on twitter.
      • Great solution! It helped me a lot. This could enter on the formIt core code as an adition as an option for the other kind of message... It would be cool.
          ----
          Daniel Melo
          • 19388
          • 297 Posts
          It helped me so much. Thanks!
            • 7976
            • 36 Posts
            Your welcome guys,

            Here is an update, it add a few features such as the "and" between the last words. (also sorry for not the greatest markup, I haven’t got any time for it to make it more ’clean’)

            <?php
            /* Snippet parameters */
            $checkValidation = (!$checkValidation)?false:true; /* Show Warning msg or let FormIt run this snippet */
            $htmlTag = (!$htmlTag)?'p':$htmlTag; /* The HTML Tag used for the warning container */
            $showIntro = (!$showIntro)?true:false; /* Show the intro text */
            
            $delimiter = (!$delimiter)?', ':$delimiter; /* Delimiter between labels */
            $ucfirst = (!$ucfirst)?false:true; /* Uppercase first charater of the label */
            
            $errorClass = (!$errorClass)?'error':$errorClass; /* Error class */
            $introClass = (!$introClass)?'contactUs':$introClass; /* Intro class */
            
            if(!$checkValidation) { /* Let FormIt run this to see if a validation failed */
            	/* Create global variables */
            	if(!$modx->FormItTmpArray) {
            		$modx->FormItTmpArray = array();
            	}
            
            	/* Create variable that contains all the pre-defined validators */
            	if(!$modx->FormItTmpValidate) {
            		$validateTmp = explode(',',$validate);
            		$tmpValidate = array();
            		foreach($validateTmp as $k => $v) {
            			$v = trim(ltrim($v),' ');
            			$keyd = explode(':',$v);
            			$tmpValidate[$keyd[0]] = array();
            			foreach($keyd as $ka => $va) {
            				if($keyd[0] != $ka) {
            					$tmpValidate[$keyd[0]][$ka] = $va;
            				}
            			}
            		}
            		$modx->FormItTmpValidate = $tmpValidate;
            		unset($tmpValidate);
            	}
            
            	/* Check if the validation failed and pass on variables */
            	if ($validator->errors[$key] && $validator->errors[$key] != "") {
            		$modx->FormItTmpArray[] = array(
            			"error" => strip_tags($validator->errors[$key]),
            			"key" => $key,
            			"value" => $value,
            			"validation" => $modx->FormItTmpValidate[$key]
            		);
            		return false;
            	} else {
            		return true;
            	}
            	
            
            } else { /* Show warning message or an intro text */
            
            	if(count($modx->FormItTmpArray)==0) { /* Visitor first view, show intro text if enabled */
            		if($showIntro) {
            			$html = '<'.$htmlTag.' class="'.$introClass.'">'.$modx->lexicon('formit.formIntro').'</'.$htmlTag.'>';
            			return $html;
            		} else {
            			return;
            		}
            	} else { /* Validator failed: Show warnings */
            		$validateWarning = array();
            		$tmp = array();
            		$i = 1;
            		foreach($modx->FormItTmpArray as $k => $v) { /* Loop occored validation warnings */
            
            			if(in_array("isNumber",$v["validation"])) { /* isNumber */
            				if($v["value"] != "" AND !is_numeric($v["value"])) {
            					$validateWarning["isNumber"] = $modx->lexicon('formit.formErrorsNumberNotValid');
            					$tmp["isNumber"][] = $v["key"];
            				}
            			}
            		
            			if(in_array("email",$v["validation"])) { /* email */
            				if($v["value"] != "") {
            					$validateWarning["email"] = $modx->lexicon('formit.formErrorsEmailNotValid');
            				}
            			}
            
            			if(in_array("required",$v["validation"])) { /* required */
            
            				if($v["value"] == "") {
            					$tmp["required"][] = $v["key"];
            					$validateWarning["required"] = $modx->lexicon('formit.formErrorsMissing');
            				}
            
            			}
            			
            			$i++;
            		}
            
            		
            		$html = '<'.$htmlTag.' class="'.$errorClass.'"><span></span>'.$modx->lexicon('formit.formErrors');
            		
            		$i = 0;
            		foreach($validateWarning as $k => $v) {
            			if($i > 0) {
            				$html .= "<br/><br/>";
            			}
            			
            			if($k == "required" OR $k == "isNumber") {
            				$aTmp = "";
            				foreach($tmp[$k] as $ki => $vi) {
            					$vi = ($ucfirst)?ucfirst($vi):$vi;
            					if($ki == 0) {
            						$aTmp .= $vi;
            					} elseif((count($tmp[$k])-1) == $ki) {
            						$aTmp .= ' '.$modx->lexicon('formit.formAndWord').' '.$vi;
            					} else {
            						$aTmp .= $delimiter.$vi;
            					}
            				}
            				$html .= str_replace("[[+value]]",$aTmp,$v);
            			} else {
            				$html .= $v;
            			}
            			$i++;
            		}
            		
            		$html .= '</'.$htmlTag.'>';
            
            
            		return $html;
            		unset($tm,$dl,$modx->FormItTmpArray,$modx->FormItTmpValidate);
            
            	}
            }


            Lexicons:
            formit.formAndWord = and
            
            formit.formErrors = <strong>Some errors were detected in your form</strong><br/>
            formit.formErrorsMissing = The following required field(s) are missing: [[+value]].
            formit.formIntro = Your personal intro message, use below bla bla bla
            
            formit.formErrorsEmailNotValid = The email address is not valid
            formit.formErrorsNumberNotValid = The specified number is not valid: [[+value]].
            


            p.s. the lexicons where translated. Please update this to better Denglish.
              Jack of all Trades and Proud Honda Zoomer owner. Also available on twitter.
              • 13460
              • 47 Posts
              Quote from: TheWebScientist at Apr 19, 2011, 03:50 PM

              p.s. the lexicons where translated. Please update this to better Denglish.

              haha good one! joe hef don ferrie wel wink
                UI /UX designer + bit of Front-End Developer. Getting around with MODx Revolution
                • 13460
                • 47 Posts
                TheWebScientist I like your snippet, good job.

                I’m wondering if FormItValidator also can catch errors triggered in FormIt itself. What I mean is I gave a field minLength=^4^-constrain but no error-message. How could I accomplish this?
                &validate=`contact_name:required:FormItValidator:stripTags:minLength=^4^,


                I’m thinking between 2 options to throw errors. 1st is your snippet along with jQuery to throw a div with these errors on top of the form. 2nd is throw errors in inputfields HTML5 placeholder-property. Hmm have to deside. But for now just fiddling with FormIt and your custom validator to get a grasp of MODx.

                EDIT; and what I would like is that I somehow could define a alternative for [[+value]] eg. my input fot name is contact_name.

                As you problably will understand by know I’m not a devver grin I’m more of a visual designer. With User Centered Design in mind throwing clear errors is important. Not in my case The following required field(s) are missing: contact_message. I know I could alter the name fields but I kind of used to develop in English but the website actually is in Dutch.
                  UI /UX designer + bit of Front-End Developer. Getting around with MODx Revolution
                  • 7976
                  • 36 Posts
                  Hey Raymond, Thanks for the compliment smiley Also sorry for the long reply as Im currently to busy with delivering an application.

                  Currently its quiet easy to extend this snippet. It already depends on the build-in validator, however its important that you put the ’validation’ in front of the ’FormItValidator’, see the below example.

                  &validate=`contact_name:required:minLength=^4^:FormItValidator:stripTags,


                  Then you can do something like this after the ’required’ if statement wihtin the snippet (around line 85):
                  			if(in_array("minLength",$v["validation"])) { /* minLength */
                  				$tmp = explode('=',$v["key"]);
                  				$val = $tmp[1];
                  				$val = str_replace("^","",$val);
                  				$val = (int)$val;
                  
                  				if(count($v["value"]) != $val) {
                  					$tmp["required"][] = $tmp[0];
                  					$validateWarning["minLength"] = $modx->lexicon('formit.formErrorsMinLength');
                  				}
                  
                  			}
                  


                  I haven’t test the code above and I cant really test this because I’m too busy for now.
                  Also I agree with your idea to put in a label name somewhere. I was thinking something like:

                  &validate=`contact_name:required:minLength=^4^:FormItValidator=^Contactnaam^:stripTags,
                    Jack of all Trades and Proud Honda Zoomer owner. Also available on twitter.
                    • 13460
                    • 47 Posts
                    Okay! I’m going to try what you’re suggesting. About the html5-placeholder it doesn’t work so not usable. It’s purpose is only as placeholder, so it doesn’t work. I think the cleanest solution usability-wise is to throw errors in the values-properties but then the error-message should be handled as improper input.

                    Greetz!
                      UI /UX designer + bit of Front-End Developer. Getting around with MODx Revolution
                      • 7976
                      • 36 Posts
                      Yeah, both the placeholder and the javascript wouldnt be a good solution. Since javascript won’t work in the Lynx browser and the placeholder isn’t crossbrowser, yet.

                      What you could do - to fix this quickly - is:
                      After line 103 add:
                      $vi = str_replace("_"," ",$vi);


                      Then name your input something as "contact_naam".
                      If your uppercase first is on and with the addition above you will get "Contact naam".

                      I will add this new features to my todo list.
                      Dunno to be honest when I can resume the todo list.
                        Jack of all Trades and Proud Honda Zoomer owner. Also available on twitter.