JavaScript Form Validation Script: More features

This is in continuation of the JavaScript Form Validation script in this page. In this page, we will see some of the advanced features of the script.

Showing all the form validation errors together in a message box

If you want to show all the error messages together, then just call the EnableMsgsTogether() function as shown below.

frmvalidator.EnableMsgsTogether();


Form validation messages in single message box

See the form validation demo

Showing the form validation errors on the page itself

You can display the validation errors on the page itself.

Here are the steps:

  1. Create a place on the page for displaying the errors
  2. create a DIV on the page for the errors the DIV should be named as {formname}_errorloc
    where {formname} is the name of your form.
    Example:

    <div id='myform_errorloc' class='error_strings'></div>
    
  3. Enable on-page error display
  4. Call the EnableOnPageErrorDisplaySingleBox() function to enable on page error display.
    For example:

    frmvalidator.EnableOnPageErrorDisplaySingleBox();
    frmvalidator.EnableMsgsTogether();
    

See the form validation demo here

Showing the error messages next to the input element

Form validation error message
Here are the steps:

  1. Create a place to display the error message next to the input elements
  2. For example place a DIV next to the input element and have it ID of the format:
    {formname}_{inputname}_errorloc
    Example:

    <div id='myform_Name_errorloc' ></div>
    <input type="text" name="Name" />
    
  3. call EnableOnPageErrorDisplay()
  4. frmvalidator.EnableOnPageErrorDisplay();
    frmvalidator.EnableMsgsTogether();
    

Conditional Validations

Sometimes it may be required to validate certain fields only on certain conditions. For example, a textbox ‘Other’ needs to be filled only when ‘Other’ radio option is selected.

conditional validation
Here is how to add a condition to a validation:
There is an optional 4th parameter to the addValidation() function. If you pass a condition, that condition will be checked before running the validation.
Example:

frmvalidator.addValidation("hearabout_other","req","Please fill-in this textbox",
        "VWZ_IsChecked(document.forms['myform'].elements['hearabout'],'Other')");

VWZ_IsChecked() is a handy function included in gen_validatorv4.js script that can be used to check the ‘checked’ status of radio group or check box. The first parameter is the input object and the second parameter is the value.

If it is a drop down list, you can use the VWZ_IsListItemSelected() function

frmvalidator.addValidation("city_other","req","Please fill-in the city name",
        "VWZ_IsListItemSelected(document.forms['myform'].elements['city_list'],'Other')");

VWZ_IsListItemSelected(list_object, item_value)
The first parameter is the drop down list object and the second is the value of the item.

Triggering the validations when custom submitting the form

The validation script uses the form’s onsubmit event to trigger the validations. If you are submitting the form using code, for example on clicking a hyperlink, the onsubmit event is not triggered :

<a href='#' onClick="document.yourform.submit()">Submit Form</a>

You can trigger the validations by explicitly calling the form’s onsubmit like this:

<a href='#' onClick="if(document.yourform.onsubmit()){document.yourform.submit()}">Submit Form</a>

Making it a bit neater:

<a href="javascript: submitform()">Submit</a>
<script type="text/javascript">
function submitform()
{
    if(document.myform.onsubmit())
    {
        document.myform.submit();
    }
}
</script>

Next: Save your time coding forms and validations

Just Choose Validations!
Simfatic Forms is a feature-rich web form maker.
You just have to choose the validations. More info & downloads

Comments on this entry are closed.

  • Can anyone help me with an onblur statement?

  • I was looking at the code and I am wondering how would you clear out the textboxes that had the wrong items in it after it tells you that it is wrong?

  • hi, i am having trouble using the function/class that validates if at least one check box is selected in the form before submitting it. I am using this code:

    <script language=”JavaScript” type=”text/javascript”>
    var frmvalidator  = new Validator(“frmSubjectReservation”);
    frmvalidator.EnableOnPageErrorDisplaySingleBox();
    frmvalidator.EnableMsgsTogether();
     
    frmvalidator.addValidation(“chkSubject”,”selmin=1″,”Select at least one subject”);
    frmvalidator.addValidation(“chkSubject”,”selmax=1″,”You can only register for one suject”);
     
    </script>

    It wont show anything or does something like displaying the error.
    Please help. Thanks.

  • hey, I am just starting to use the script and I must say it is very good. There is one problem though, with list boxes, I can not make it a required field plus the “frmvalidator.addValidation("Country","dontselect=000"); ” is not working. (I have substituted “Country” with the value that I need.) I have followed the instructions but its not working, please help. Thanks

    • make ‘000’ the value of the default option. i.e.
      <option value”000″>Choose Country</option>
      hope that helped,

  • Hello,
    I have an issue with a Wysiwyg editor such as the one I’m typing in for this very comment I’m entering now (the app is CKEditor). I want to make sure the user enters at least 150 characters into the editor. I used the ‘minlen=150’ validation. When the user enters 150+ characters and submits the form they’re getting the error message the first time. If they simply just click submit again it goes through the second time. The instance of the validator is called as below. The tipbody is the one I’m concerned with.

     <script type=”text/javascript”> 
      var frmvalidator  = new Validator(“TipForm”);
      frmvalidator.EnableOnPageErrorDisplay();
      frmvalidator.EnableMsgsTogether(); 
      …
      …
      frmvalidator.addValidation(“tipbody”,”minlen=150″,”*Please Enter a Tip [Minimum Length – 150 characters]”); 
      …
      …
     </script>

    Thank you,
    Josh

  • very glad to see this code, now just 30 kb of js code is enough for validating all the forms on my projects.

  • Hi,
    I am using gen_validator for a couple of years now and I am very pleased with this ‘product’.
    Your addition of conditional validation is great.
    However, for my situation I needed a validation if a certain value was NOT set on a specific select box.
    So I added below function to your gen_validatorv4.js script:
     

    function VWZ_IsListItemNotSelected(listname, value)
    {
    for (var i = 0; i < listname.options.length; i++)
    {
    if (listname.options[i].selected == false && listname.options[i].value == value)
    {
    return true;
    }
    }
    return false;
    }

    This works fine, so possibly it is a good idea to add it to your script as well (and make the same type of adjustment for VWZ_IsChecked in a new function VWZ_IsNotChecked)?
     
    Kind Regards and keep up the good work on this fine piece of scripting,
    Erwin Beelen

  • Hi,

    Great code, just wondering though.
    I have got two email boxes, (one for confirmation). If the user doesn’t fill in the two fields correctly can the javascript highlight the two input boxes where the user got it wrong?

    Many Thanks,

  • hi:

    i am just starting to use this script. I am getting the following error when the page first loads. “‘ frmvalidator’ is null or not an object “. I have verified that all of the variables are correct. the form is in an asp page on a corp network.

    • You haven’t linked to the gen_validatorv4.js main script.

      • I have the js file linked in the header section of the asp page.

  • Having trouble with form spam. I have added hidden field that I want to be empty. Trying to code custom validation to make it stop form submission if hidden field has input. Can this be done?
    Thanks for you input!

    • Coding such a validation in Javascript will not help. Because those submissions are from ‘spam bots’ who won’t care about JavaScript. You have to do the spam protection validations on the server side script.

  • hi dude,

    i just had to tell you thats a really cool work you’ve done there.
    took me 3hrs but i finally got it to use on my website.

    thanks a million !!!!!

    & many thanks,
    sameer.

  • Love it!

    I need to put a restriction, so the users only be able to type specific numbers on two first numbers on the phone number input.

    For example, users are disable to put other numbers than 0 and 1.
    Then, It has to be:
    01xxxxxxxxx
    01987634534
    01958557464

    Any solution to modify this validation?

    Thanks in advance 🙂
    once again, I Love it!

  • This is prefect and has really helped me out. The one thing I am trying to accomplish though is putting an exclamation image next to the error message, I tried inserting it in the CSS but the text goes ontop, I tried inserting it in the error code message but it just breaks the script. Can anyone help.

    Many thanks

    Scott

  • Hi,

    First of all, thank you for this incredible code. I am trying to use the more advanced functionality and I am not sure I am causing the error or if I stumbled on a bug.

    I have a inputtext AmountReal1 that only should be required if the drop down(select) banco1 is at the value 0

    var frmvalidator = new Validator(“trans”);
    frmvalidator.EnableMsgsTogether();

    frmvalidator.addValidation(“amountReal1″,”req”,”Por favor preencha o valor do depósito.”, “VWZ_IsListItemSelected(document.forms[‘trans’].elements[‘banco1′],’0’)”);

    Not sure where it is going wrong. Although I tried to step through the code, somewhere in there I am getting lost and not able why it is not preventing the page from submitting.

    I would certainly appreciate if someone could help me.

    Take care,

    Michel

    • Please make sure that the value of the selected item is 0 (It is the value, not the index) also, the names are case sensitive; AmountReal1 or amountReal1?

  • Any chance you could add date format validation for mm/dd/yyyy and dd/mm/yyyy? Love the script, very handy! Sure, could force the user to fill in three numeric fields, but would be handy to validate a single field with that specified format.

  • thank you.. helped me in my project
    loved the script

    jst one doubt.. hw do i make showing error messages next to input elements coloured or bold??
    where do i make those changes??
    please help!!

      • thank you for the help prasanth..
        i got it…
        i did not exactly follow what you asked me to do… rather i put a <b> tag in before the error string– something like this—
        frmvalidator.addValidation(“name”,”req”,”<b>you forgot to enter name</b>”);

        and it worked fine…
        thank you for the script!!

        • oh oh… what i mean is in the error string .. just when it starts i inserted a html bold tag…

  • If form name and input name have _ in their values, will the “” work?

    • im referring to the code that gives the errors next to the offending input elements.

  • I would like to know how can i make both appear together on the same page, single box and message next to the input element.
    1. single box
    rmvalidator.EnableOnPageErrorDisplaySingleBox
    frmvalidator.EnableMsgsTogether

    2. Create a place to display the error message next to the input elements
    frmvalidator.EnableOnPageErrorDisplay
    frmvalidator.EnableMsgsTogether

    • Both together is not supported. Either of them at a time

  • Hi, thanks for this awesome script. I’ve been playing around with a few things in the file/code on a site I just inherited that uses this script and I’m a little confused. I can’t find where the configuration setting is located to modify the recipient address and/or subject line. I haven’t been able to identify any server-side scripts that would process this functionality.

    TL;DR – I need to modify the email address the form is sent to and the subject and i can’t find where those values are stored.

    thanks in advance for your assistance!

    • This is only form validations script and is in JavaScript. The emailing code should be in a server side script like PHP or ASP

  • Hi,
    Love the validator. I am wanting to print a form if valid – by using window.print()

    How can I adapt the code to do this?

    Many thanks

    Peter