logo

Form Validator R2.0


This database demonstrates an alternative method of using JavaScript to validate domino forms before their submission to the server. The difference with this database being that the validation routines are totally modular. All you need to do is pass an array of fields in to a JavaScript function and it will do the rest.

The norm seems to be to write a function that checks the value of each field explicitly, which, as discussed in this article, can mean having to write very long functions. For forms with lots of fields this also means editing the function whenever new fields are added to or removed from the form.

Using this method the validation function simply receives an array of fields as an argument and loops through this array whilst validating each field.

The array also includes information on the type of data that is expected so that domino doesn't get upset with text in a number field or a non-date in a date field. There is also an option for each number or date field checked to make sure it is within a certain range.

The routines in the database can handle the following field types:
  • Text Fields
  • Single-Select Dropdown Boxes
  • Multi-Select Dropdown Boxes
  • Text-areas
  • Radio Buttons
  • Check Boxes
  • File Uploads
As well as the following types of data:
  • Text
  • Dates
  • Date Ranges
  • Numbers
  • Number Ranges
  • E-mail Addresses
  • File Types
Take a look at the database to see what I mean. It is developed in R5 but the code and principles should work in all versions of both client and browser.

Note that the later version are very JavaScript intensive and, if you want to get "under the hood", not for the lighthearted. However, you can use it simply by copying all the ".js" pages into your database and then call the functions from any form in your databases.

Current Version:
Version 20. introduces support for Netscape, both version 4.5 and 6.0. There are also a few smaller fixes, including a bug with single radio-buttons and check-boxes. The new CSS files provide a new look to distinguish this from prior versions.

Previous Version:
Version 1.8 introduced the principle of using arrays to store the fields that need validating.

Version 1.6 introduced the ability to validate various data types.

Version 1.5 introduced the ability to specify which fields are to be validated, using the field's ID attribute to store various information.

Version 1.0 was the original idea and worked by simply looping through every field in the form and checked for an entry.

Feedback

    • avatar
    • David Marsh
    • Sun 26 Nov 2000

    Some minor enhancement suggestions!

    A couple of things to keep in mind when using the JavaScript validator.

    The first is to do with two digit and four digit years being returned by Domino.

    When using the @Adjust formula or Now() in LotusScript, if the regional settings on the servers OS that Domino is running indicate a short date style like this dd/MM/yy then obviously you get two digits for the year. It is recommended to change the settings to dd/MM/yyyy and restart the domino server.

    Something for developers to keep in mind.

    A small change to the validator script to simplify the use of javascript arrays and regular expressions is to make the following change to the DateComponents function in the global.js page.

    function DateComponents(dateStr, format) {

    var results = new Array();

    REPLACE THESE TWO LINES -------------------------------------------------------- var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; var matchArray = dateStr.match(datePat); -------------------------------------------------------- WITH THIS ONE -------------------------------------------- var matchArray = dateStr.split( /\/|-/ ) --------------------------------------------

    if (matchArray == null) { return null; }

    // parse date into variables if (format.charAt(0)=="d"){ //what format does the server use for dates? results[0] = matchArray[1]; results[1] = matchArray[3]; } else { results[1] = matchArray[1]; results[0] = matchArray[3]; } results[2] = matchArray[4]; return results; }

    • avatar
    • Jake
    • Fri 16 Mar 2001

    Problem to be aware of!!

    Version 1.8 has a problem validating check-boxes and radio-buttons when there is only one of them in the group.

    Not sure why yet. Anybody got any bright ideas?

    Expect a fix in version 2.0 along with some other enhancements.

    Jake -CodeStore

  1. Problem with Generate HTML for all Fields

    I commonly check off this property on my Forms and when I incorporated Validator R2.0, the calendar picker would not put the picked date into the date field of my form. If I unchecked the property, then the picker worked fine. However, I have had such good luck with keeping this property checked that I hate to uncheck it and suffer unintended consequences. Any idea what is happening and how I can use the Validator 2.0 with that property checked?

    Thanks,

    Luis

    PS Brilliant work!!

    1. Re: Problem with Generate HTML for all Fields

      Hello!

      I was hoping that someone could help me understand when to use the "Generate HTML for all fields" property, and when not to use it...

      I have been using this property on a project for a while getting all kinds of unpredicted results (forms that won't display in a browser etc.). Finally I decided not to use it.

      What I did instead was using computed for display fields for those fields I needed on the form (using Javascript...), like this: <input name="test" value="[computed for display field]" type="hidden">

      The problem is that I use a WebQuerySave agent that uses the information in one of these fields. The only way I can get the agent to accept the values is to make the field editable and place it outside the <input>-tag.

      If some of you understands what I am trying to explain and what my problem is, please try to help...

      Thanks Ove

      Show the rest of this thread

      • avatar
      • Russ McBride
      • Thu 23 Oct 2003

      Re: Problem with Generate HTML for all Fields

      I had the same problem. After looking at the source code I noticed that there were duplicate fields being generated. I removed the "name = " parameters from the DateFormat and Browser HTML fields.

      After making this change it worked with Generate HTML for all Fields.

      Next I tried removing all of the HTML associated with those two fields and that worked, too. In other words, just make them two hidden Notes fields without the HTML code to hide them.

      Thanks to everyone who contributes here. It is appreciated!

    • avatar
    • fogg
    • Fri 31 Aug 2001

    JavaScript Form Validator R2.0

    It seems that JavaScript Form Validator R2.0 is in trouble to verify day an month value in a date field when these values < 10.

    It seems that Rolf Strijdhorst has the same problem. The problems comes in the function validate script_valid.js code. For example when you have parseInt(dateBits[1]) with a month < 10, you obtain the 0 value.

    Rolf, if you still need the correction i can send it to you.

    1. Re: JavaScript Form Validator R2.0

      I had trouble getting Validate function to work properly for all months. I had to replace the

      parseInt(dateBits[1])

      with simply

      dataBits[1]

      in the three New Date calls in the valiDate function. Seems to work fine without the parseInt. Is there some reason why parseInt is needed here?

      Show the rest of this thread

  2. Works a treat mate - CHEERS

    Ey up lad,

    Just thought I'd give you a bit of public accolade (to make up for the Spider Man pyjama jokes!).

    I like that and shall ensure that we adopt it as a standard now you've left.

    Lots of love

    Matty

    1. Re: Works a treat mate - CHEERS

      Tell HSBC they can stick it up their proverbial ass. No, actually, better not. I still need Nigel's reference.

      So when I was there nobody listens and now I've left you all using my stuff. Typical. Give me my job back.

      See you next week anyway mate... do you still want me to wear the Spider Man jim-jams??

      Jake

      Show the rest of this thread

    2. Re: Works a treat mate - CHEERS

      Hi.

      I like your validation form, Works great.

      Only 1 problem, not sure if it is me but the Date Validation does not always see the date as being correct.

      i changed the Min and Max values and some dates shown invalid.

      If you try the original database JavaScript validater Ver 2 that is the one on this site then try the date 31/12/2003 it does not work, giving the error taht the date is not in the date range of 1976-2004.

      Someone else try it and see if they get the same problem?

      If it is a bug then what should i change to fix it?

      Regards

      Mike

  3. Huge timesaver

    Thanks for the work put into this. It has made things much easier for my transition into Javascript.

    It could use a slight update, though. The valiDATE function is assuming a 20th century date for a date with a two digit year value. I made it assume a 21st century date and all is well.

    Thanks again

    • avatar
    • Ben
    • Tue 22 Jan 2002

    Lifesaver!

    I've just been dumped into a JS-heavy app and was getting really worried....until now. Hurry up and set up a donation system for codestore....you might be able to stop looking for work (well not really, but you might at least be able to eat in the meantime!).

    Seriously, great effort Jake.

    1. Re: Lifesaver!

      If you can understand the JS I use in this app you are better than I am. I get lost myself when I go back in there now. Must have been on steroids when I wrote all that.

      Ok, you ask and you get. There is now a donation system on the homepage.

      Jake -codestore

      Show the rest of this thread

    2. JS Validation - problem with DIV tags

      Jake, thanks very much for making the JS Validator available, it has saved me (a JS novice) so much work.

      I have come across one problem in my implementation of it, and wonder if I am taking the wrong approach.

      I have split a form into pages using DIV tags to hide the relevant pages. When the user clicks on a 'Next' or 'Previous' icon a little JS function is called to display the relevant section.

      Only problem is, I had to make a slight amendment to your OnFailure routine to make this work. When it got to the obj.focus part an error was occuring as the object could not be given focus if it was in a hidden section. So, I added some code to tell the routine which section to display depending on which field had failed.

      Worked fine. Ah..one problem. Now the code is not so standard anymore! So now when I want to validate a different form that has some of the same field names but does not use DIV tags I get an error. The only way round this I can think of is to modify the functions again to pass the name of the form. But I didn't really want to modify the code yet again........is there another way.

      I guess you're going to be far too busy with the new contract to even think about this again...but if you do get a chance.

      Best of luck with the contract anyway!

    • avatar
    • Matt
    • Fri 15 Feb 2002

    Validate a time value : hh:mm am/pm

    Has enhanced this routine to check for a valid time format?

    1. Re: Validate a time value : hh:mm am/pm

      Finally, I can give a little back ...

      var timeExpression uses Regular Expression to define the input pattern, hh:mm AM (or PM), to match. Using the Reg Exp match event, valresult will return null if the pattern is not fulfilled.

      <script>function checkTime(timeV,message) { var textTime = document.forms[0].elements[timeV].value; var timeField = document.forms[0].elements[timeV] var timeExpression = /^(\d{2}):(\d{2})\s{1}([AP]M)$/; var valresult = textTime.match(timeExpression); if (valresult==null) { alert("Time entry in " + message + " is invalid. Please enter a valid time in hh:mm AM or PM format (e.g. 08:00 AM)"); timeField.value = ""; timeField.focus(); } } </script>

      In your time field onChange event, pass the field name and a message (to customize the alert for the multiple time fields).

      Although I didn't in this example, on a valid pattern match (i.e. valresult is not NULL) you can use the array of grouped patterns (defined by parans grouping in the Regular Expression). returned from the above Regular Expression valresult. So, valresult[1] = hh, valresult[2] = mm valresult[3]= AM or PM (valresult[0] is the entire string). With hh and mm segmented, now I can validate to make sure hh < 24 and mm < 60.

      Show the rest of this thread

    2. Re: Validate a time value : hh:mm am/pm

      Thanks codestore for great collections.This site has really helped me a lot

    3. Re: Validate a time value : hh:mm am/pm

      Please give the solution to add the date time in this format.

  4. Justifying Changed Values!

    Howdy!

    First of all, this validation logic is a great help, Jake! Good work! I'm going to use this as a standard everywhere.

    I've been in the process of adding different functions to it in order to be able to do more validation. For example, it now deals with tabbed tables (tho' could be improved), and some other issues. I have created another function which is used to see if a field value has been modified. The function pops up a js 'prompt' which the user MUST enter a value which will be saved in the document history. It works quite well, but I am struggling to integrate it into the "doSubmit" function. Here it is:

    function doSubmit(f, v){ if ( v ){ var a = new Array(); a[a.length] = [f.WhateverField, 'Whatever Field'] justifyChange( f.Field);

    if ( validateRequiredFields( f, a ) ){ return true; }else{ return false; } } else { return true; } }

    Here's the "justifyChange" function:

    function justifyChange( obj ) { var lbl = obj.name; var oldVal = obj.defaultValue; var newVal = obj.value; if (oldVal != newVal && oldVal != "" ) { var why = prompt ("For what reason has the " + lbl + " been modified?", "" ); if ( why == null ) { alert( "You must enter a reason for modifying the " + lbl + "."); return false; } else var reason = lbl + ": " + oldVal + " changed to " + newVal + " (" + why + ")"; f.History.value = reason; } }

    (I apologize if the indentations don't come out well.)

    It works fine if the user enters a reason at the 'prompt'. The prompt comes up, and the value is properly enter in the "History" field and the document is submitted. However, if a user hits 'Cancel', the document will be saved anyways. The "return false;" after the "(why == null)" doesn't seem to stop the submit!!

    I hope this is clear enough, but if you need it cleared up, please lemme know. Any help would be greatly appreciated!

    Thanks, in advance!

    Steve in Montreal.

    1. Re: Justifying Changed Values- Solved!

      Hello! Well, I solved my previous post! I created a function to justify a field value modification. It's integrated into the validation process.

      Thanks, anyway! ;)

      Steve in Montreal.

  5. Netscape 6 not validating

    Jake,

    Great validation tool. I have it working great in Netscape 4.x and IE 5.x and IE 6.x. When I use Netscape 6.x I run into problems. The validation never takes place. I tried your suggestion in a earlier thread about adding it directly to a button onClick event and it still didn't work.

    I would love to toss Netscape out the window but our organization has employees that would rather use this browser. Any help would be greatly appreciated.

    Thanks Mike

    1. Re: Netscape 6 not validating

      Hi Jake.. thanks a lot for this wonderful validation tool.. wnated to ask your opinion on the Browser trends..

      Is it a good move to develop for NS7, if we have a choice ? as Release 6 is too buggy and 7, seems to support the some Std DOM . Looks like 7 is going to be the taken as the de-facto std .. Jake do you agree?

      Thanks , Thomas

      Show the rest of this thread

    • avatar
    • TippChick
    • Thu 14 Mar 2002

    Similar but different

    Have scanned through several of the responses etc, and I haven't seen any mention of this, so I thought I'd throw it it to see if you can make use of it. Apologies if I am repeating others...

    I use very similar code for validation, except when I call the Submit, I dont pass in the field names of the fields to be validated.

    I give all required fields a class of Mandatory ( in the HTML Properties ), and in the validation code, I loop through all the elements and only validate the ones where element[i].className = 'Mandatory'.

    Then I use element[i].type to decide which field type I have to validate... ( Oh yes, I also stop it from validating hidden fields, when element[i].type == 'hidden'. )

    The Error message to be returned, can then pick up element[i].title ( which you fill with suitable values )

    Nice thing about this, is you can set up a Style for Mandatory, and set all fields to Yellow ( I prefer moccasin ) to show user that they are mandatory.

    An extension on this is that you can set up other classes, such as Date or MandatoryDate or length1to4 etc, which will validate all your date fields, and so on.

    The radio/checkbox elements need to be tested a different way, becuase otherwise they get validated as many times as there are options in the field. So in the validateRadio function you need to do this to get the group instead of the element

    var radiofield = eval('document.forms[0].'+field.name)

    and then the code is the same as Jakes, and in the calling function, I only validate radio elements, if the element[i].name <> element[i+1].name ( ie its the last element in the radio group ).

    Works for me.

      • avatar
      • Jake Howlett
      • Thu 14 Mar 2002

      Re: Similar but different

      Afraid I've got to say I did that too ;-)

      If you look through the version history of all the availble versions (bottom of the article) I think it's v1.5 that used the field's ID to do just the same thing.

      I got rid of this so as to improve the chances of it working in Netscape.

      I also find it easier to see which are the required fields when in an array versus having to look through the attributes of every field.

      Nice to see other people thinking along the same line though. You know what they say about great minds ... ;-)

      Jake -codestore

    1. Date Validation?

      Firstly, this thing is a life saver.

      I do have a question about it however.

      Can I use it to validate 2 date fields with each other? I need to check to make sure Date B is greater than Date A.

      I wrote some script like this:

      if ((f.DateA.value) > (f.DateB.value)) { alert("The Date B can't be before Date A"); f.DateB.focus(); return false }

      But I can't work out where it should fit without it causing me errors.

      Any help would be appreciated.

      Cheers Simon

      Show the rest of this thread

  6. Can I use a field to specify required fields?

    Hi,

    First of all: I love this site!

    I have many different forms with different required fields on my database and I like to use just one Validate page or subform. I also want to hand it over to administrators to deside which fields on which form should be required.

    I would like to make a "ReqFields" for required fields and a "ReqFieldsText" for description of required fields on the current form. The Value of these fields comes from a view, which lookup to a administrator-defined form (see the ex.)

    ReqFields value:@DbLookup("" : "NoCache"; ""; "viewValidate"; Seminar;3)

    ReqFieldsText value::@DbLookup("" : "NoCache"; ""; "viewValidate"; Seminar;4)

    ReqFields are defined in the view like this: @If(FirstNameValidate="*";"FirstName";"")+ @If(LastNameValidate="*";";"+"LastName";"")+ @If(CompanyValidate="*";";"+"Company";"")

    ReqFieldsText are defined like this: @If(FirstNameValidate="*";"Please enter your first name";"")+ @If(LastNameValidate="*";";"+"Please enter your last name";"")+ @If(CompanyValidate="*";";"+"Please enter your first company";"")

    So if the administrator sets a "*" in field "FirstNameValidate" than the field FirstName should be required.

    Now, how can I refer to the Reqfields and ReqfieldsText on the form instead of to specify each required field on the Validate Page?

    Thank you for any help. Armand Tara

  7. Problem with Rich Edit Applet

    I have problems when I use the rich edit applet and try to save the document using JavaScript (submit()). The information in the applet is lost. In addition is a problem to refresh the information in the rich text applet when the document begins to edit.

    1. Re: Problem with Rich Edit Applet

      Two things:

      1) Don't use the applet!

      2) If you have to, read the thread hanging from [<a href="cmnts/3DEBE6E483F3E3F286256B99001AE828?OpenDocument">this comment</a>]

      Jake -codestore

    2. Fix: Problem with Rich Edit Applet

      When Notes wants to save the data from the applet, it runs the _getEditAppletData() (spelling?) javascript function, which takes the output of all RT applets on the form and updates the value of the field it's being substituted for.

      Whenever you need to check the value of the field, run the same function.

      Another problem with the applet is that onChange events are not recognised. To get round this, I defined my own event handlers for the focus() and blur() events (which are recognised). The new handlers simply store the value on entry (focus) and compare with the value on exit (blur). Because one object blurs before the other is focused, this works satisfactorily (code avail. on req.)

      Show the rest of this thread

      • avatar
      • dcS
      • Wed 15 Jan 2003

      Re: Problem with Rich Edit Applet

      I have the exact same problem. When I use a Rich Text applet, the data does not save via document.forms[0].submit(). If I change the type to HTML, all is fine.

      I do not want to do that.

    • avatar
    • James
    • Tue 1 Oct 2002

    Date Validation

    I'm having StartDate & EndDate as time/Date fields in Notes form, but when i'm using validate function , it's taking dates as text. e.types ="text" for Time/Date fields .

    e.g.: a[a.length] = [f.DateEnd, f.DateEnd,f.DateStart ,'dd/mm'];

    this doesn't work . Pls help.

      • avatar
      • Stan Rogers
      • Thu 3 Oct 2002

      Re: Date Validation

      Until hard typing comes along for HTML fields, that's the way it works on the web. If you want to validate the values as date/time, then you need to create Date objects in JavaScript from the text values held in the HTML fields. If you check your HTML forms carefully, you'll see that all single-value "keyboard entry" fields are text fields -- they can be type converted in JavaScript (often implicitly rather than by casting methods) and will be converted to Notes data types on submit.

    1. date format (dd/mm/yyyy)

      i dunno how to format the date dd/mm/yyyy in javascript in dynamic form..let say i've dynamic row in form built using DOM.i can't implement date format dd/mm/yyyy in IE v5.5 for dynamic row. u have an idea..pls reply me asap...ok.. regards, noor

      Show the rest of this thread

    • avatar
    • andy heller
    • Thu 2 Jan 2003

    can't find the .js files

    i have tried to use your form validator in domino designer, and for some reason it cannot find the .js files which causes the submit not to execute.

    One other thing, is there a way off of the javascript submit to redirect the user to a "Form has been sent" confirmation page.

  8. problem doing validation on Notes client

    Jake, this is really great. It's very helpfully. Thank you for all your good work. However, I do have a question on using this for Notes client.

    I find out that even though there is a if ( doSubmit(document.forms[0], true ) ) document.forms[0].ValidationStatus.value = "1"; document.forms[0].submit();

    statement, Notes client will still pop out a window asking if you want to save or not.

    The workaround for this is to call the doSubmit function in the "OnSubmit" event of the form and have the below in the "Save with Validation" button: @Command([FileSave]); @If( ValidationStatus = "0"; @Return(""); ""); @Command([FileCloseWindow])

    But, because of the nature of the application, I have to call the doSubmit function in an action button instead of in the "OnSubmit" event, is there anyway around it in javascript? how do I translate the [@If( ValidationStatus = "0"; @Return(""); "");] statement?

    You might be too busy, but when you have a chance, I'd appreciate your advice.

      • avatar
      • Jake Howlett
      • Mon 12 May 2003

      Re: problem doing validation on Notes client

      Hi,

      Sorry to have to say this but I can't help. I have absolutley no knowledge of the use of JavaScript with the Notes client. All I know about is using Domino with the browser. Sorry.

      Jake

    • avatar
    • Fredrich
    • Tue 20 May 2003

    Checkbox

    Hi, First, excuse my bad english, it´s not my mainlanguage. Thanx for a great application, it´s help me a lot. I´m new in JS and a wonder how i do if a want to check if a checkbox is marked, and if its not, a want the script check other fields.

    Kind regards Fredrich

    1. How to validate date (javascript)

      Can you tell me how to validate date field (ex. pay_date) cannot greater than todays date.

  9. Bug in (2.0)

    HI

    I believe there may be a bug in the current version (2.0).

    It seems there is a subtle bug in the function valiDate(), which can cause problems when validating dates using upper or lower conditions.

    It is caused by the use of the javascript function 'parseInt()'. This function contains a bug. See here for more of an explanation: http://www.breakingpar.com/bkp/home.nsf/Doc?OpenNavigator&U=87256B280015193F8725 6C85006A6604

    (if you want to try it then use the validation code to test a date containing a month of either 08 or 09 - this one took me a while!)

    thanks.

    1. Re: Bug in (2.0) ... easy fix ...

      ...

      Easy fix shown below.

      <code> function valiDate(obj, min, max, format){ dateBits = dateComponents(obj.value, format); if (dateBits == null) return false;

      //Check it is a valid date first ... //Now check whether a range is specified and if in bounds var theDate = new Date(dateBits[2], parseInt(dateBits[1],<b>10</b>) - 1, dateBits[0]);

      if ( min ) { minBits = dateComponents (min, format); var minDate = new Date(minBits[2], parseInt(minBits[1],<b>10</b>) - 1, minBits[0]); if ( minDate.getTime() > theDate.getTime() ) return false; } if ( max) { maxBits = dateComponents (max, format); var maxDate = new Date(maxBits[2], parseInt(maxBits[1],<b>10</b>) - 1, maxBits[0]); if ( theDate.getTime() > maxDate.getTime() ) return false; } return true; } </code>

      Interestingly i did notice that you have used the bug fix on this post http://www.codestore.net/store.nsf/cmnts/F3E50993039AF1EB86256C10002FA6A5?OpenDo cument

      (Thanks for the cool work jake)

      Show the rest of this thread

    2. Number Validation

      Hi,

      I am getting errors validating a number field where a language (Danish) in IE uses a comma to represent a decimal point. Getting the users to use a period(.) is not possible.

      Thanks

      Show the rest of this thread

    • avatar
    • Charlotte
    • Tue 30 Sep 2003

    Some Suggestions

    Works really great, though I had some trouble trying to understand at first.

    There are some things that are not available.

    1. Minimum number of digits users must input. 2. Format of the phone number.

    (^_^)

    • avatar
    • Ian
    • Fri 5 Mar 2004

    Refresh fields on keyword change

    Suppose the field Radio Group: was set to Refresh fields on keyword change and rubbish was entered into the date field. Then during data entry another selection was made on the Radio Groupd field.

    In this event the form can be submitted with an ivalid date causing the page to error.

    What is the solution to this issues.

    1. Re: Refresh fields on keyword change

      i have a html page with 3 form on it. i want when one form submit, only this form refreshed and other part of page stay like before (like Gmail page). i need javascript that can do this.pleases answer me as soon as posible.

      Show the rest of this thread

  10. Phone number validation added

    This is a great resource! I modified the code to include an improved phone field validation feature. Included here is the complete script_valid.js file updated to include the new "phone" parameter...

    /********************************************************* Set of JavaScript functions used for validation

    JavaScript Validation 2.0.X, 19/Mar/2001 Jake Howlett, http://www.codestore.org/

    Updated on 12/Mar/2002 to allow periods (.) as date-separators

    Update on 30/June/2004 by charles@parra.com to allow for validation of phone numbers based on the SmartWebby.com DHTML phone number validation script (http://www.smartwebby.com/dhtml/)

    **********************************************************/

    /*********************************************************** validateNumber() This function checks that the value of a field is a number and, optionally within a certain range. Arguments: val = Value to be checked min = Optional minimum allowed value max = Optional maximum allowed value ************************************************************/

    function validateNumber(val, min, max){ if ( isNaN( val ) ) return false; if ( min && val < min ) return false; if ( max && val > max ) return false; return true; }

    /*********************************************************** dateComponents() This function splits a date in to the day, month and year components, depending on the format supplied. Used by Date Validation routine. Arguments: obj = Input whose value is to be checked format = date format, ie mm/dd or dd/mm ************************************************************/

    function dateComponents(dateStr, format) { var results = new Array(); var datePat = /^(\d{1,2})(\/|-|\.)(\d{1,2})\2(\d{2}|\d{4})$/; var matchArray = dateStr.match(datePat); if (matchArray == null) { return null; } //check for two digit (20th century) years and prepend 19. matchArray[4] = (matchArray[4].length == 2) ? '19' + matchArray[4] : matchArray[4];

    // parse date into variables if (format.charAt(0)=="d"){ //what format does the server use for dates? results[0] = matchArray[1]; results[1] = matchArray[3]; } else { results[1] = matchArray[1]; results[0] = matchArray[3]; } results[2] = matchArray[4]; return results; }

    /*********************************************************** valiDate() This function checks that the value of a date is in the correct format and, optionally, within a certain range. Arguments: obj = Input whose value is to be checked min = Optional minimum allowed value max = Optional maximum allowed value format = date format, ie mm/dd or dd/mm ************************************************************/

    function valiDate(obj, min, max, format){ dateBits = dateComponents(obj.value, format); if (dateBits == null) return false;

    //Check it is a valid date first day = dateBits[0]; month = dateBits[1]; year = dateBits[2];

    if ((month < 1 || month > 12) || (day < 1 || day > 31)) { // check month range return false; } if ((month==4 || month==6 || month==9 || month==11) && day==31) { return false; } if (month == 2) { // check for february 29th var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day==29 && !isleap)) { return false; } }

    //Now check whether a range is specified and if in bounds var theDate = new Date(dateBits[2], parseInt(dateBits[1]) - 1, dateBits[0]);

    if ( min ) { minBits = dateComponents (min, format); var minDate = new Date(minBits[2], parseInt(minBits[1]) - 1, minBits[0]); if ( minDate.getTime() > theDate.getTime() ) return false; } if ( max) { maxBits = dateComponents (max, format); var maxDate = new Date(maxBits[2], parseInt(maxBits[1]) - 1, maxBits[0]); if ( theDate.getTime() > maxDate.getTime() ) return false; } return true; }

    /*********************************************************** validateEmail() This function checks that the value of a field is a valid SMTP e-mail address ie x@xx.xx Arguments: obj = Input whose value is to be checked

    Original source: http://javascript.internet.com Author: Sandeep V. Tamhankar (stamhankar@hotmail.com)

    Note: Work in progress = validate SMTP OR Notes Canonical ************************************************************/

    function validateEmail( obj ) { var emailStr = obj.value; var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid if ( !reg1.test( emailStr ) && reg2.test( emailStr ) ) { return true; } else { return false; } }

    /*********************************************************** locateFileUpload() Returns a handle to the file upload control on a form. Used to get around the fact that there is no consistent way to refer to the element cross-browser. ***********************************************************/ function locateFileUpload( f ) { for(var i = 0; i < f.elements.length; i ++) if( f.elements[i].type=='file' ){ return f.elements[i]; } }

    /*********************************************************** validateFileType() This function checks that the type of file being uploaded is allowed Arguments: obj = The File Upload control. fTyp = Allowed file types ************************************************************/

    function validateFileType( obj, fTyp ) {

    dots = obj.value.split("."); fType = "." + dots[dots.length-1];

    if ( fTyp != null && fTyp.indexOf(fType) == -1 ) return false;

    return true; }

    /*********************************************************** validateFileLimit() This function checks that the value in a file upload Arguments: obj = The File Upload control cur = Current number of file attachments max = Limit on allowed files ************************************************************/

    function validateFileLimit( obj, cur, max ) {

    if ( cur >= max ) return false;

    return true; }

    /*********************************************************** OnFailure() This function returns the failure message to the user and sets focus on the input in question. Arguments: obj = Input element on which to return focus lbl = Field Label to prepend on to the message msg = Array value for message to give the user ************************************************************/

    function OnFailure( obj, lbl, msg ){ var msgs = new Array(); msgs["text"] = " is a required field. \n\nPlease enter a value."; msgs["textarea"] = " is a required field. \n\nPlease enter a value."; msgs["select-one"] = " is a required field. \n\nPlease select an entry."; msgs["select-multiple"] = " is a required field. \n\nPlease select an entry."; msgs["checkbox"] = " is a required field. \n\nPlease select an entry."; msgs["file"] = " is a required upload. \n\nPlease select a file."; msgs["fileType"] = " requires certain file types. \n\nPlease select a valid file type."; msgs["fileLimit"] = " is a limited file upload. \n\nPlease reduce number of attachment(s) first."; msgs["radio"] = " is a required field. \n\nPlease select an entry."; msgs["number"] = " is a numeric field. \n\nPlease enter a valid number."; msgs["date"] = " is a date field. \n\nPlease enter a valid date."; msgs["email"] = " is an address field. \n\nPlease enter a valid e-mail address."; msgs["phone"] = " is a phone field. \n\nPlease enter a valid phone number."; if(msg[1] || msg[2]){ //upper/lower bound ranges have been specified if(msg[1] && msg[2]){//range term = ( msg[0] == "date" )? " ("+msg[3]+")" : ""; alert(lbl + msgs[msg[0]] + term + " between " + msg[1] + " and " + msg[2]); } else if (msg[1]) {//lower bound term = ( msg[0] == "number" ) ? " greater than " : " (" + msg[3] + ") after "; alert(lbl + msgs[msg[0]] + term + msg[1]); } else {//upper bound term = ( msg[0] == "number" )? " less than " : " (" + msg[3] + ") before "; alert(lbl + msgs[msg[0]] + term + msg[2]); } } else {//no range given alert(lbl + msgs[msg[0]]); } obj.focus(); return false; }

    /*********************************************************** isSomethingSelected() This function is passed an object of type redio group or check box. It then loops through all options and checks that one of them is selected, returning true if so. Arguments: obj = Reference to the parent object of the group. ************************************************************/

    function isSomethingSelected( obj ){ for (var r=0; r < obj.length; r++){ if ( obj[r].checked ) return true; } }

    /*********************************************************** validatePhone() DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)

    Function checkInternationalPhone was renamed to validatePhone and is used to verify if the given value is a possible valid international phone number : This function first removes all non-digit characters which are allowed in phone numbers. These delimiters are declared in the lines (found in the beginning of the code) :

    var phoneNumberDelimiters = "()- " var validWorldPhoneChars = phoneNumberDelimiters + "+"

    Now that all valid delimiters are removed we just check if the remaining value is an integer and that it has at least a certain number of digits (given by the variable 'minDigitsInIPhoneNumber'). ************************************************************/ // Declaring required variables var digits = "0123456789"; // non-digit characters which are allowed in phone numbers var phoneNumberDelimiters = "()- "; // characters which are allowed in international phone numbers // (a leading + is OK) var validWorldPhoneChars = phoneNumberDelimiters + "+"; // Minimum no of digits in an international phone no. var minDigitsInIPhoneNumber = 10;

    function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; }

    function stripCharsInBag(s, bag) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; }

    function validatePhone(obj){ var strPhone = obj.value; s=stripCharsInBag(strPhone,validWorldPhoneChars); return (isInteger(s) && s.length >= minDigitsInIPhoneNumber); } /*********************************************************** end of validatePhone() ************************************************************/

    /*********************************************************** validateRequiredFields() This function is passed an array of fields that are required to be filled in and iterates through each ensuring they have been correctly entered. ************************************************************/

    function validateRequiredFields( f, a ){

    for (var i=0; i < a.length; i++){ e = a[i][0];

    //checks input types: "text","select-one","select-multiple","textarea","checkbox","radio","file"

    switch (e.type) { case "text": if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["text"]); if ( a[i][2] ) { switch ( a[i][2][0] ){ case "number": if ( !validateNumber(e.value, a[i][2][1], a[i][2][2]) ) return OnFailure(e, a[i][1], ["number", a[i][2][1], a[i][2][2]]); break case "date": if ( !valiDate(e, a[i][2][1], a[i][2][2], a[i][2][3]) ) return OnFailure(e, a[i][1], ["date", a[i][2][1], a[i][2][2], a[i][2][3]]); break case "email": if ( !validateEmail(e) ) return OnFailure(e, a[i][1], ["email"]); break case "phone": if ( !validatePhone(e) ) return OnFailure(e, a[i][1], ["phone"]); break default: break } } break case "file": //make sure AT LEAST one file gets attached if ( a[i][2][1] == 0 && trim(e.value) == "" ) return OnFailure(e, a[i][1], ["file"]); if ( trim(e.value) != "") { //check type of file that is being uploaded if ( a[i][2][0] != null && validateFileType( e, a[i][2][0] ) == false ) return OnFailure(e, a[i][1], ["fileType"]); //check that file limit has not been reached if ( a[i][2][2] != null && validateFileLimit( e, a[i][2][1], a[i][2][2] ) == false ) return OnFailure(e, a[i][1], ["fileLimit"]); } break case "textarea": if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["textarea"]); break case "select-one": if ( e.selectedIndex == 0 ) return OnFailure(e, a[i][1], ["select-one"]); break case "select-multiple": if (e.selectedIndex == -1) return OnFailure(e, a[i][1], ["select-multiple"]); break

    default: //must be a checkbox or a radio group if none of above

    if ( !e[0]) {//handle single item group first switch (e.type) { case "checkbox": if ( !e.checked ) return OnFailure(e, a[i][1], ["checkbox"]); break case "radio": if ( !e.checked ) return OnFailure(e, a[i][1], ["radio"]); break default: break } } else { //handle multi-item groups switch (e[0].type) { case "checkbox": if ( !isSomethingSelected( e ) ) return OnFailure(e[0], a[i][1], ["checkbox"]); break case "radio": if ( !isSomethingSelected( e ) ) return OnFailure(e[0], a[i][1], ["radio"]); break default: break } } break } } return true; }

  11. HTML Password Type Fields

    I am using this code to do some field validationon my form it it all works great except for one minor issue.

    I have a field that has HTML attributes of TYPE=Password. THe valdiation code will not check if that field is null.

    In my JSHeader I have added the foolowing code

    if ( f.request_login_typecmp.value == "2" ) a[a.length] = [f.request_cnfpassword, 'Confirm Password is a required field' ];

    if ( f.request_login_typecmp.value == "2" ) a[a.length] = [f.request_password, 'Password is a required field' ];

    It however does not get picked up as being null. If I remove the HTML attributes of TYPe=Password it traps the null field

    Any help would be greatly appreciated.

      • avatar
      • Jake
      • Wed 25 Aug 2004

      Re: HTML Password Type Fields

      For security reasons I would guess that the browser does not allow JavaScript to read any password fields, even if it's just to check whether it's blank or not. Can't think of any way round this. Maybe you could look at my more recent article about Server Side Data Validation.

    1. Re: HTML Password Type Fields

      Sir, i want to made a form in which i want to use type="password" for that user write pasword . and who tag is avail able by using i read the password in text form . "Actually i want to made this type of password " Example Password=**** i want to understand **** in form of text . Please send me mail , with solution , try to send me complet coding of form Ur site is excellent . Thanks

      Show the rest of this thread

  12. Validate number of zeros

    Jake or anyone else! Any chance you've got anything I can tag onto the validation page which checks to see that a number field ends in three zeros? Have a requirement to enter values in thousands. Thanks Jackie

  13. Form Validator R2.0 - updating array

    Hello,

    Have included the validator code into my notes form and it works well.

    I told some of the fields no longer require validation.

    So I removed them from the regFields array and reset index. When I test this form it appears to be validating exactly the same as before. As if I haven't changed the form.

    I assumed it was a caching problem in my IE browser so I deleted the temporary file. This didn't fix the problem.

    Do you have any suggests to fix this problem.

    (I believe the validator is fine.)

      • avatar
      • Jake
      • Thu 24 Feb 2005

      Re: Form Validator R2.0 - updating array

      Check for this Yvonnne http://codestore.net/store.nsf/unid/BLOG-20041019?OpenDocument

    1. Re: Form Validator R2.0 - updating array

      Hello Jake

      I wonder if you know what reg.expressions to use for different date formats?

      I guess that the form validator reg.expression is based on format dd/mm/yyyy, but I would like to support yyyy/mm/dd.

      Really, is there any resource on the web that shows examples for this.

    • avatar
    • Yvon
    • Sun 17 Jul 2005

    How to use the nsf file

    I downloaded the zip file and I didnt know how to use the nsf file included thanks

      • avatar
      • Jake Howlett
      • Mon 18 Jul 2005

      Re: How to use the nsf file

      It's a Lotus Notes database file. If you didn't know that then I'm guessing it's of no use to you.

  14. Error message

    I tried using the validation but I get an error message on: if ( validateRequiredFields( f, a ) ){

    I copied the required documents but can not get it to work. Thanks.

    1. _getEditAppletData() problem with Sun JVM

      I'm running into a problem when we switch over to the Sun JVM instead of the Microsoft VM. The nsf is using the form validator, but that is returning fine. The app hangs when _getEditAppletData() is called. With the MS VM, everything is fine. It hangs totally with the SUN JVM. any ideas?

      • avatar
      • Jake
      • Sat 17 Mar 2001

      Re: Netscape 4 and 6

      Thanks John. Glad you like it ;-)

      Hmm, Netscape 6 does indeed seem to ignore the onsubmit event of the form. Wonder why when it works okay in version 4!?

      The work around is to by-pass the onsubmit and do the validation straight from the button. Put the following in the button's onClick event:

      if ( doSubmit( document.forms[0], true ) ) document.forms[0].submit();

      As for the submission of empty check-boxes. Leave it with me and I'll see if I can address it in version 2.0....

      Jake -CodeStore

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:



Navigate other articles in the category "Forms"

« Previous Article Next Article »
None Found   Keyword Refresh R2.0

About This Article

Author: Jake Howlett
Category: Forms
Keywords: JavaScript; Validate; Submit;

Attachments

validation15.zip (33 Kbytes)
validation10.zip (14 Kbytes)
validation16.zip (56 Kbytes)
validation18.zip (51 Kbytes)
validation20.zip (65 Kbytes)

Options

View Online Demo
Feedback
Print Friendly

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »