Using JavaScript validation

GreyHead 20 Jul, 2007
Hi,

Caution: I'm no JavaScript expert so there may be errors in this post. If you find any let me know and I'll fix them.

ChronoForms makes it easy to include validation JavaScript with your form but there are some problems in using JavaScript from other sources or existing forms.

Mostly there are two problems:[list]
  • ChronoForms changes the form name and the JavaScript doesn't recognise it.
  • How to call the JavaScript validation - what code to put where.
  • [/list]I'll describe here a basic method that should fix most of these problems. There are other methods that may work as well or better for you.

    The form name

    ChronoForms changes the form name you use in the Form Manager. If you enter 'my_form' the ChronoForms form will be called 'ChronoContact_my_form'. This is probably the biggest cause of JavaScript validation problems.

    Validation scripts usually start with a line like 'function checkForm()' or 'function checkForm(form)' and these two handle the form name in different ways.

    Style 1: 'function checkForm()'

    The form is usually addressed with the code 'document.{form_name}' e.g. 'document.my_form'

    To use this style with ChronoForms you would need to find and replace each 'document.my_form' with 'document.ChronoContact_my_form'. This is tedious and has to be repeated if you want to use the same validation with another form.

    Instead I suggest that you change your JavaScript to the second style of function.

    Style 2: 'function checkForm(form)'

    This style of function uses the JavaScript variable 'form' to identify the form and the actual form name is passed to the function when it is called.

    If your JavaScript has the other style, then change the function header to the 'checkForm(form)' style and replace every occurrence of 'document.{form_name}' with 'form' so that 'document.my_form.some_code' becomes 'form.some_code' etc.

    Calling the JavaScript

    Once you have edited the JavaScript to use the 'checkForm(form)' you can call it simply by adding this code into the ChronoForms 'Form tag attachment' field:
    onSubmit="return checkForm(this)"
    Using 'this' here will mean that the correct form name is automatically passed to the JavaScript.

    The 'return' means that the form will only be submitted if the JavaScript validation returns 'true' - this is how validation scripts are usually written so is unlikely to be a problem.

    Here is a very simple example of a validation script written like this, it simply validates that the form field 'name' is not empty :
    function checkForm(form)
    {
     if(form.name.value == ""«»)  {
       alert("Please enter your name!"«»);
       return false;
      }
     return true;
    }


    Bob<br><br>Post edited by: GreyHead, at: 2007/07/20 11:34
    goranbaxy 26 Oct, 2007
    Here is my JS code:
    Some text is on Croatian😟
    but if I catch some time I'll translate it!
    function validate_email(field,alerttxt)
    {
    	with (field)
    	{
    		apos=value.indexOf("@"«»)
    		dotpos=value.lastIndexOf("."«»)
    		if (apos<1||dotpos-apos<2) 
    		  {alert(alerttxt);return false}
    	}
    }
    
    function checkForm(form)
    {
    	/* IME */	  	
    	 if(form.name.value == ""«»)  {
    	   alert("Niste unjeli ime!"«»);
    	   return false;
    	  }
    	/* PREZIME */	  
    	 if(form.subname.value == ""«»)  {
    	   alert("Niste unjeli prezime!"«»);
    	   return false;
    	  }
    	/* MAIL */	  
    	with (form)
    	{
    	if (validate_email(email,"Niste unjeli ispravnu mail adresu!"«»)==false)
    	  {email.focus();return false}
    	}  
    	/* TELEFON */
    	 if(form.tel.value == ""«»)  {
    	   alert("Niste unjeli broj telefona!"«»);
    	   return false;
    	  }	
    	/* ADRESA */
    	 if(form.adresa.value == ""«»)  {
    	   alert("Niste unjeli adresu!"«»);
    	   return false;
    	  }	
    	/* KUĆNI BROJ */
    	 if(form.kbroj.value == ""«»)  {
    	   alert("Niste unjeli kućni broj!"«»);
    	   return false;
    	  }		
    	/* POÅ TANSKI BROJ */
    	 if(form.posta.value == ""«»)  {
    	   alert("Niste unjeli poštanski broj!"«»);
    	   return false;
    	  }		
    	/* GRAD */
    	 if(form.grad.value == ""«»)  {
    	   alert("Niste unjeli grad!"«»);
    	   return false;
    	  }		
    	/* ŽUPANIJA */
    	 if(form.zupanija.value == "21"«»)  {
    	   alert("Niste izabrali županiju!"«»);
    	   return false;
    	  }		  
    	  /* Ovo se izvršava nakon svih provjera! */
    	  return true;
    }
    
    Max_admin 26 Oct, 2007
    hi goranbaxy,

    do you put the checkform(this) in the right field in Chronoforms? is your form online somewhere ?

    Max<br><br>Post edited by: admin, at: 2007/10/26 15:02
    Max, ChronoForms developer
    ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
    ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
    goranbaxy 26 Oct, 2007
    In "Form tag attachment:" I have: "enctype='multipart/form-data' onSubmit="return checkForm(this)""
    everthing is working but it's still not online as it needs some design.
    I have put the the html + js code in " Share your forms with others"
    Max_admin 26 Oct, 2007
    Conversation moved here :<br><br>Post edited by: GreyHead, at: 2007/11/06 15:58
    Max, ChronoForms developer
    ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
    ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
    sailsmart 16 May, 2008
    On the validating a form thread, can I just press the validate at the bottom of the live form which redirects to a website which shows all line errors, then the choice to use html tidy to fix. This usually helps when using an alternate editor like Dreamweaver. I think I still then have to take out some of the head tags and form tags. Does anyone else do this?
    a6april 16 May, 2008
    How do I add more fields to this code???
    function checkForm(form) 
    { 
     if(form.Name.value == "")  { 
       alert("Please Enter Your Name!"); 
       return false;
      } 
     return true; 
    }
    GreyHead 17 May, 2008
    Hi sailsmart,

    I'm not completely sure what you are asking here.

    In form validation we are usually talking about using some JavaScript or PHP to check that the form user has made the right kind of entry in a form field (for example, an email address is actually an email address and not a nonsense string).

    You can use HTML Tidy to check that your form code is using valid HTML - that's also useful, you can run the page url through one of the on-line validators. I'd recommend that you use FireFox with the FireBug extension which is by far and away the best web-page debugger. (There's also an HTML validator extension for FireFox.)

    Bob
    GreyHead 17 May, 2008
    Hi a6april,

    Don't. If you are looking for simple 'required' field validation then use the Validation built in to ChronoForms. Go to the Validation tab turn it ON, set the library to Mootools for Joomla 1.5 (or leave as prototype for Joomla 1.0.x) and put a comma separated list fo field names in the 'required' box.

    No more messing with special scripts.

    Bob
    a6april 17 May, 2008
    Thanks Bob,

    I had no idea that Validator even worked, I did not know to put it on Mootools, wow that just saved me about 3 or 4 headaches.

    I do have a question on how to add the email validation. I scrolled down to the
    7- validate-email (a valid email address)

    I then put the email field in there, however when I test the form, the email does not get validated and the form gets sent right on through with the email field blank. (I did double check for form field case mis-match.

    Also where is the css to change the color of the text that pops up and says required?, can I change that text?
    GreyHead 17 May, 2008
    Hi a6april,

    You probably need to put the 'email' field in 'required' too. The 'validate-email' field (and the others) work on the basis of 'if there is an entry is it a valid entry' so blank entries are OK. That makes sense when you think about.

    The validation works with css classes. Error messages show up with class="validation-advice" so just add some css for that.

    Bob
    a6april 17 May, 2008
    Are you saying on line 139 of the validation.js file

    advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'


    I need to edit this, i do not see any css attached to it unless I have to figure out how to say add a color to the code above

    or is there a css file somewhere I can't find?
    a6april 17 May, 2008
    AAAHHHHHHH!

    Hi Bob, I found it on the mooValidation.js file on line 90 character number: 110 I changed
    setStyle('display','none')

    to
    setStyle('color','red')


    I am sure there are all sorts of edits you can do there to get creative but I will look into that later, but I hope this helps someone else for now

    Thanks Bob for always being there!!:)
    GreyHead 17 May, 2008
    Hi a6april,

    If you aren't using any css of your own you can just add a snippet at the beginning of the form html:
    <style type="text/css">
    form .validation-advice {color:red;}
    </style>
    Bob

    PS I think that changing display:none to something else may have unexpected side-effects.
    a6april 17 May, 2008
    I think your correct, lol I just noticed that the form I am using has a lot of required fields, they are getting cut off after so many characters, could that be a side effect your talking about?

    I tried to change the properties of the paramsall in phpMyAdmin for longer text but that is not working..any suggestions?
    a6april 17 May, 2008
    That css snippet worked out great Bob Thanks, however I still have to increase the max character of text allowed in the 2 form fields
    on the validation page:
    1 - required (not blank)
    11- validate-selection

    They both say LONGTEXT in the phpMyAdmin I thought that should be correct but it stops off at 100 characters, how do I increase that?
    a6april 17 May, 2008
    I have narrowed it down to somewhere in the admin section in the html it has a maxchar=100, But I do not know where to edit that at, any suggestions will be greatly appreciated..Thanks in advance
    Spetter 17 May, 2008
    You can change it in administrator/components/com_chronocontact/admin.chronocontact.html.php at line 765 and further. I changed mine like:

    input type="text" name="params[val_required]" 
    id="params[val_required]" class="inputbox" size="50" 
    maxlength="1000" 
    value="<?php echo $paramsvalues->val_required; ?>"
    GreyHead 17 May, 2008
    Hi a6april,

    In the version I have here for Joomal 1.5 it's line 769 of admin.chronocontact.html.php
    <input type="text" name="params[val_required]" id="params[val_required]" class="inputbox" size="50" maxlength="100" value="<?php echo $paramsvalues->val_required; ?>">
    and the others are a few lines below

    Bob

    PS I thought that Max had extended or parameterised that so I may not have the latest version installed.
    a6april 17 May, 2008
    Hi Bob,

    Maybe thats my problem, I don't have admin.chronocontact.html.php

    where is that located? is it out side the components folder?
    a6april 17 May, 2008
    Nevermind, Brain freeze, I found it, (Duh... in the admin folder lol)
    a6april 18 May, 2008
    Under the Form Validation in the Admin section there are 11 Fields of types:

    1 - required (not blank)
    2- validate-number (a valid number)
    3- validate-digits (digits only)
    4- validate-alpha (letters only)
    5- validate-alphanum (only letters and numbers)
    6- validate-date (a valid date value)
    7- validate-email (a valid email address)
    8- validate-url (a valid URL)
    9- validate-date-au (a date formatted as; dd/mm/yyyy)
    10- validate-currency-dollar (a valid dollar value)
    11- validate-selection
    12- validate-one-required

    I have a single Agree to terms check box that gets past the form checker that is required.
    I have it listed in 1 and also 12, I also tried removing it from 1 and putting it in 12. I also tried 11 as well and still It gets past it, I will keep it auto checked for now but if anyone figured this out please let me know.
    GreyHead 18 May, 2008
    Hi a6april,

    Please will you post the code snippet for the checkbox and I'll take a look.

    Bob
    hefesto 18 May, 2008
    I know very few Javascript, so you'll have to excuse me if my question sounds too simple (or even too stupid):

    Would it be possible to make a conditional validation quite easily? For example, would it be possible to check if at least one of two fields has been correctly filled? It would be very useful if you give your users the option of giving a contact email OR a phone number. Just in case they don't have an email...

    Thanks.
    GreyHead 18 May, 2008
    Hi hefesto,

    It's possible but not necessarily easy. You'd need to extend the JavaScript library that ChronoForms uses. There are some basic instructions if you look at Andrew Tetlaw's Dexagogo site and list.

    Bob
    hefesto 18 May, 2008
    I'll take a look at it and post here with my results.

    Thanks once again for your outstanding support Bob😉.
    hefesto 18 May, 2008
    I've noticed that the validation library can be switched to Mootools in Chronoforms. I usually use in my sites many Mootools' powered extensions, so maybe it would be more useful for me if I coded my solution using it instead of Prototype. What do you recommend me?
    GreyHead 18 May, 2008
    Hi hefesto,

    If you already use Mootools then stay with it, mixing JavaScript frameworks on the same page often causes problems.

    Bob
    OCS 23 May, 2008
    I'm using prototype to validate my form. Works fine when JavaScript enabled.

    But how can I submit the form via JavaScript and validate form?

    If I use input type="button" with onclick="submit();" it doesn't validate the form and sends it. (JS enabled)

    If I use input type="submit" and JS is disabled it sends the form without validation.
    Max_admin 23 May, 2008
    Hi OCS,

    You have 2 options, use Chronoforms validation only or use your own validation only!🙂

    cheers

    Max
    Max, ChronoForms developer
    ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
    ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
    Ep2 02 Jun, 2008
    In my Version CE/Jommla don't interpet the " , so nothing is working.
    Now i use " instead of " , i know thats not fine, but its still work

    Joomla 1.5.3 (German Version)

    P.S. Sorry for my bad english :d
    GreyHead 05 Jun, 2008
    Hi Ep2,

    There are some problems with old posts on the forum since Max updated. Make the following changes in any code that looks odd:

    replace " with "
    replace < with <
    replace > with >
    replace & with &

    Bob
    h3g 15 Jul, 2008
    Could you give us an clear example on how the option "validate-selection" works?
    Max_admin 15 Jul, 2008
    add the SELECT field name there and make the first choice in the SELECT list with a value = "" or "0" and it will ask the user to choose something other than the first one which is expected to be something like "Please select"

    Cheers

    Max
    Max, ChronoForms developer
    ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
    ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
    joeey 28 Jul, 2008
    Hi everyone, is it possible to include my own verification codes together with ChronoForms's validation codes together ? I need to verify that there are 6 numbers and a letter in one of my textbox. Besides that, ChronoForms's validation codes are sufficent.
    GreyHead 28 Jul, 2008
    Hi joeey,

    Yes the validation is extensible, either by adding your own functions in the JavaScript box or by hacking the validation.js (Prototype) and/or moovalidation.js (MooTools) scripts.

    See Andrew Tetlaw's Dexagogo site and Google Group for more information.

    Bob
    joeey 28 Jul, 2008
    I wish to validate a textbox that only allows 6 digits and 1 letter. Is the code below able to do that ?
    ['validate-admin', 'Please enter 6 digits and a letter for your admin number.' function (v) {
    	           return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{6}[a-zA-Z]?)$/.test(v)
    }]
    GreyHead 28 Jul, 2008
    Hi joeey,

    There some RegExp junk in there too I think; try /^[1-9]{6}[a-zA-Z]$/

    Bob
    joeey 29 Jul, 2008
    Hi Bob, thanks for the code.
    Bullfn33 01 Aug, 2008
    I don't know much of anything about JS but I need to use it in order to validate the radio buttons on my form, being that there is a small text box in between each radio button group. I found this basic form validation script from a JS website that looks like it is in the recommended format but I don't know what I need to change to make it work. I only really need the radio validation part. Can anyone tell me exactly what part that is? Thanks for any help on this

    function f55Verify(form){
     if (typeof(f55frm)=='string'){ f55frm=form.f55frm; }
     var f55els,f550,f55mess,f55ck;
     var f55messary=[];
     var f55all='';
     if (f55frm.fail){ f55RemoveMarker(f55frm.fail); }
     f55frm.ary=[];
     f55els=f55frm.elements;
     for (f550=0;f550<f55els.length;f550++){
      if (f55els[f550].name&&!f55els[f550].className.match('f55exc')&&!f55els[f550].exc){
       if (f55FalseBGColor){ f55els[f550].style.backgroundColor=f55FalseBGColor; }
       f55els[f550].mnme=f55els[f550].name;
       if (f55els[f550].title){ f55els[f550].mnme=f55els[f550].title; }
       f55els[f550].nme=f55els[f550].name.replace('[]','');
       if (!f55all.match(f55els[f550].nme)){ f55frm.ary.push(f55els[f550]); window['f55'+f55els[f550].nme]=''; window['f55ary'+f55els[f550].nme]=[]; }
       window['f55ary'+f55els[f550].nme].push(f55els[f550]);
       f55els[f550].pass=false;
       if (f55els[f550].type=='text'||f55els[f550].tagName=='TEXTAREA'){
        f55mess=false;
        if (f55els[f550].special){ f55mess=true; f55Special(f55els[f550],f55messary); }
        if (!f55mess){
         f55mess=f55els[f550].mnme+'\n'+(f55els[f550].mess||'Please Complete');
         f55messary.push(f55mess);
         if (f55els[f550].value.length>0){
          f55messary.length--;
          f55els[f550].pass=true;
         }
        }
        f55CkBGColor(f55els[f550]);
       }
       if (f55els[f550].type=='radio'||f55els[f550].type=='checkbox'){
        if (f55els[f550].mm){ f55Special(f55els[f550],f55messary); }
        else {
         f55mess=f55els[f550].mnme+'\n'+(f55els[f550].mess||'Please Check One');
         if (!f55all.match(f55els[f550].nme)){ f55messary.push(f55mess); }
         if (f55els[f550].checked){
          f55messary=f55messary.remove(f55mess);
          window['f55ary'+f55els[f550].nme][0].pass=true;
         }
        }
        f55CkBGColor(f55els[f550]);
       }
       if (f55els[f550].tagName=='SELECT'){
        f55mess=f55els[f550].mnme+'\n'+(f55els[f550].mess||'Please Select');
        if (f55els[f550].selectedIndex<1){ f55messary.push(f55mess); }
        else { f55els[f550].pass=true; }
        f55CkBGColor(f55els[f550]);
       }
       if (!f55all.match(f55els[f550].nme)){
        f55all+=f55els[f550].nme+',';
       }
      }
     }
     if (f55messary.length>0){
       if (f55frm.mark){ f55Marker(f55frm); }
       if (f55alt){ alert(f55messary.join('\n\n')); }
       return false;
     }
     return true
    }
    
    function f55CkBGColor(f55bgobj){
     if (!f55TrueBGColor){ return; }
     var f55col=f55FalseBGColor
     if (window['f55ary'+f55bgobj.nme][0].pass){ f55col=f55TrueBGColor; }
     for (f551=0;f551<window['f55ary'+f55bgobj.nme].length;f551++){
      window['f55ary'+f55bgobj.nme][f551].style.backgroundColor=f55col;
     }
    }
    
    Array.prototype.remove=function(f55ary){
     var f55ary0;
     for (f55ary0 in this){ if (this[f55ary0]==f55ary){ this.splice(f55ary0,1); } }
     return this
    }
    
    
    //-->
    GreyHead 01 Aug, 2008
    Hi Bullfn33,

    Sorry, I've not the slightest idea and the code is far too cryptic for me to sort it out easily.

    Bob
    Bullfn33 01 Aug, 2008
    Edit: Never mind, I found a much simpler code and used your fixes in the first post of the thread and it worked great. thanks
    Abhishka 16 Mar, 2009
    Thank you so much..you made my day.
    This topic is locked and no more replies can be posted.