home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 2000 July / macformat-092.iso / Dreamweaver 3 / Configuration / Behaviors / Actions / Validate Form.js < prev   
Encoding:
Text File  |  1999-12-01  |  10.9 KB  |  295 lines

  1. // Copyright 1998 Macromedia, Inc. All rights reserved.
  2.  
  3. //*************** GLOBAL VARS  *****************
  4.  
  5. var helpDoc = MM.HELP_behValidateForm;
  6.  
  7. //******************* BEHAVIOR FUNCTION **********************
  8.  
  9. //Validates a form by checking the values in multiple text fields.
  10. //Accepts a variable number of args, in pairs as follows:
  11. //  objName  - simple object name, or object ref for Netscape (ex: document.myForm.Email)
  12. //  x        - ignored (for backward compatibility)
  13. //  theCheck - what to check: [R|N][isEmail|isNum|inRange<fromNum>:<toNum>], where:
  14. //                R       - some value is Required (non-empty)
  15. //                N       - value is Not required
  16. //                isEmail - value must have an @ with at least 1 char before & after (x@y)
  17. //                isNum   - value must be a number
  18. //                inRange - value is between the two numbers, inclusive
  19. //             Examples:
  20. //               user must enter *something*:     R
  21. //               a required Email field:          RisEmail
  22. //               an optional Age field:           NisNum
  23. //               a required # of orders, max 100: RinRange1:100
  24. //
  25. //Finds the object.
  26. //Gets the value from the text input or text area and runs the check as follows:
  27. //  if the field is not empty
  28. //    if theCheck is "isEmail", ensure we have at least x@y, else give error
  29. //    else if theCheck isn't just "R", all that's left is isNum or inRange
  30. //      if field is not a number give error
  31. //      else if field not in range give error
  32. //  else if theCheck is "R" give error
  33. //Batches up all error values and returns them in a single alert() dialog.
  34. //Also, sets the global return value to false. If this Action is paired with the onSubmit
  35. //message, it can prevent the form from submitting if there are errors.
  36.  
  37. function MM_validateForm() { //v3.0
  38.   var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  39.   for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
  40.     if (val) { nm=val.name; if ((val=val.value)!="") {
  41.       if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
  42.         if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
  43.       } else if (test!='R') { num = parseFloat(val);
  44.         if (val!=''+num) errors+='- '+nm+' must contain a number.\n';
  45.         if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
  46.           min=test.substring(8,p); max=test.substring(p+1);
  47.           if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
  48.     } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  49.   } if (errors) alert('The following error(s) occurred:\n'+errors);
  50.   document.MM_returnValue = (errors == '');
  51. }
  52.  
  53. document.VERSION_MM_validateForm = 3.0; //define latest version number for behavior inspector
  54.  
  55. //******************* API **********************
  56.  
  57.  
  58. //Checks for the existence of text fields.
  59. //If none exist, returns false so this Action is grayed out.
  60.  
  61. function canAcceptBehavior(tagStr,eventStr){
  62.   var nameArray = getAllObjectRefs("NS 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  63.   return (nameArray.length > 0);
  64. }
  65.  
  66.  
  67.  
  68. //Returns a Javascript function to be inserted in HTML head with script tags.
  69.  
  70. function behaviorFunction(){
  71.   return "MM_findObj,MM_validateForm";
  72. }
  73.  
  74.  
  75.  
  76. //Returns fn call to insert in HTML tag <TAG... onEvent='thisFn(arg)'>
  77.  
  78. function applyBehavior() {
  79.   var curFormNum,menuLength,i,chkStr,fieldName,objName,retArgs = "";
  80.  
  81.   //scan fieldMenu for values
  82.   menuLength = document.theForm.fieldMenu.options.length;
  83.   for (i=0; i<menuLength; i++) {
  84.     chkStr = getMenuValue(eval(i));
  85.     if (chkStr) {
  86.       //found a value, package up the string
  87.       fieldName = document.MM_NS_REFS[i];
  88.  
  89.       if (fieldName.indexOf(REF_UNNAMED) == 0)  //if unnamed reference
  90.         return MSG_UnnamedField;
  91.  
  92.       objName = "'" + getNameFromRef(fieldName) + "'";
  93.       if (retArgs) retArgs += ","; //add comma if necessary
  94.       retArgs += objName + ",'','" + chkStr + "'";
  95.     }
  96.   }
  97.   if (retArgs) {
  98.     updateBehaviorFns("MM_findObj","MM_validateForm");
  99.     return "MM_validateForm(" + retArgs + ")";  //return fn call with args
  100.   }
  101.   else return MSG_NoFieldsSet;
  102. }
  103.  
  104.  
  105.  
  106. //Returns a dummy function call to inform Dreamweaver the type of certain behavior
  107. //call arguments. This information is used by DW to fixup behavior args when the
  108. //document is moved or changed.
  109. //
  110. //It is passed an actual function call string generated by applyBehavior(), which
  111. //may have a variable list of arguments, and this should return a matching mask.
  112. //
  113. //The return values are:
  114. //  URL     : argument could be a file path, which DW will update during Save As...
  115. //  NS4.0ref: arg is an object ref that may be changed by Convert Tables to Layers
  116. //  IE4.0ref: arg is an object ref that may be changed by Convert Tables to Layers
  117. //  other...: argument is ignored
  118.  
  119. function identifyBehaviorArguments(fnCallStr) {
  120.   var argList, argArray, numArgGroups, i;
  121.  
  122.   argList = "";
  123.   argArray = extractArgs(fnCallStr);
  124.   numArgGroups = (argArray.length - 1) / 3; //args come in triplets
  125.   for (i=0; i<numArgGroups; i++) {          //with each NSobj,IEobj,test triplet
  126.     if (argList) argList += ",";
  127.     argList += (argArray[3*i+1].indexOf(".")==-1)? "objName,other,other" : "NS4.0ref,IE4.0ref,other";
  128.   }
  129.   return argList;
  130. }
  131.  
  132.  
  133.  
  134. //Given the original function call, this parses out the args and updates
  135. //the UI.
  136.  
  137. function inspectBehavior(upStr){
  138.   var argArray,numArgs,found,i,numTokens,theFieldNS,theChk;
  139.  
  140.   argArray = extractArgs(upStr);  //get new list of Field,Chk pairs (ignore argArray[0])
  141.   numArgs = argArray.length;
  142.   for (i=1; i<(numArgs-2); i+=3) { //with each FieldNS, FieldIE, Chk triplet
  143.     theFieldNS = argArray[i];
  144.     theChk=argArray[i+2];
  145.  
  146.     //Now that form is there, look for field name
  147.     found = false;
  148.     numFields = document.MM_NS_REFS.length;
  149.     for (j=0; j<numFields; j++) { //check if Field is in menu
  150.       if (theFieldNS==document.MM_NS_REFS[j] || theFieldNS==getNameFromRef(document.MM_NS_REFS[j])) { //if Field there
  151.         addValueToMenuItem(document.theForm.fieldMenu,j,theChk);
  152.         found = true;
  153.         break;
  154.     } }
  155.     if (!found) alert(errMsg(MSG_FldNotFound,theFieldNS,theChk)); //if Field name not found
  156.   }
  157.   document.theForm.fieldMenu.selectedIndex = 0;
  158.   displaySelection();
  159. }
  160.  
  161.  
  162.  
  163. //***************** LOCAL FUNCTIONS  ******************
  164.  
  165.  
  166. //Load the select menu with frame names.
  167.  
  168. function initializeUI(){
  169.   var niceNameSrcArray,nameArray,i;
  170.   var menuLength = 0; //menu now zero length
  171.  
  172.   //Populate the Form Menu
  173.   document.MM_NS_REFS = getAllObjectRefs("NS 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  174.   document.MM_IE_REFS = getAllObjectRefs("IE 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  175.   niceNameSrcArray = document.MM_NS_REFS;
  176.  
  177.   //Search for unreferenceable objects. <DIV id="foo"> is IE only, <LAYER> is NS only.
  178.   //if REF_CANNOT found, return empty string, and use IE refs for nice namelist.
  179.   for (i=0; i<document.MM_NS_REFS.length; i++) {
  180.     if (document.MM_IE_REFS[i].indexOf(REF_CANNOT) == 0) {
  181.       document.MM_IE_REFS[i] = ""; //blank it out
  182.     }
  183.     if (document.MM_NS_REFS[i].indexOf(REF_CANNOT) == 0) {
  184.       document.MM_NS_REFS[i] = ""; //blank it out
  185.       niceNameSrcArray = document.MM_IE_REFS; //use the IE list
  186.     }
  187.   }
  188.   nameArray = niceNames(niceNameSrcArray,TYPE_Text);
  189.  
  190.   for (i in nameArray) {
  191.     document.theForm.fieldMenu.options[i]=new Option(nameArray[i]); //load menu
  192.     menuLength++;
  193.   }
  194.  
  195.   //Store the field menu length
  196.   document.theForm.fieldMenu.length = menuLength;  //store the menu length (hack - prop not supp)
  197.  
  198.   //Select first item
  199.   document.theForm.fieldMenu.selectedIndex = 0;
  200. }
  201.  
  202.  
  203.  
  204. // Given an index into select "fieldMenu", returns any value in parens
  205.  
  206. function getMenuValue(menuIndex){
  207.   var checkStr,menuStr,startPos;
  208.  
  209.   checkStr = "";
  210.   menuStr = document.theForm.fieldMenu.options[menuIndex].text;
  211.   startPos = menuStr.indexOf("(");
  212.   if (startPos != -1)    //get previous check string
  213.     checkStr = menuStr.substring(startPos+1,menuStr.lastIndexOf(")"));
  214.   return checkStr;
  215. }
  216.  
  217.  
  218.  
  219. //Given a new text field has been selected in the menu,
  220. //loads the correct validation check settings into the checkboxes.
  221.  
  222. function displaySelection() {
  223.   var isReqd,theRadio,curFieldNum,menuStr,colonPos;
  224.  
  225.   isReqd = false;  //default settings
  226.   theRadio = 0;
  227.   curFieldNum = document.theForm.fieldMenu.selectedIndex; //get selected index
  228.   menuStr = getMenuValue(curFieldNum);  //get selection's value (in parens)
  229.   document.theForm.fromNum.value = "";
  230.   document.theForm.toNum.value = "";
  231.   if (menuStr) {
  232.     isReqd = (menuStr.charAt(0)=="R");  //true if R, false if N
  233.     if (menuStr.length > 1) {
  234.       if (menuStr.indexOf("isNum")!= -1) {theRadio = 1}
  235.       if (menuStr.indexOf("isEmail")!= -1) {theRadio = 2}
  236.       if (menuStr.indexOf("inRange")!= -1) {
  237.         theRadio = 3;
  238.         colonPos = menuStr.indexOf(':');
  239.         document.theForm.fromNum.value = menuStr.substring(8,colonPos);
  240.         document.theForm.toNum.value = menuStr.substring(colonPos+1,menuStr.length);
  241.       }
  242.     }
  243.   }
  244.   document.theForm.isReqd.checked = isReqd;  //check Required box
  245.   for (i=0; i<document.theForm.theCheck.length; i++)
  246.     document.theForm.theCheck[i].checked = (theRadio == i);
  247. }
  248.  
  249.  
  250.  
  251. //Given a selection change, gets the values from the checkboxes/radios etc.
  252. //and stores the checks in the menu next to the previous selected text field.
  253.  
  254. function saveCheckToMenu(newChk) {
  255.   var curFieldNum,isReqd,thingToAddToMenu;
  256.  
  257.   curFieldNum = document.theForm.fieldMenu.selectedIndex; //get index to swap
  258.   if (curFieldNum != null)  //if something selected
  259.     if (document.theForm.fieldMenu.options[curFieldNum].text) { //if there's a menu item
  260.       isReqd = (document.theForm.isReqd.checked)? "R" : "N";  //first char, R for required fld
  261.       if (newChk == "required") { //if they hit the "required" checkbox
  262.         newChk = getMenuValue(curFieldNum);
  263.         if (newChk) newChk = newChk.substring(1,newChk.length); //skip first char (R or N)
  264.       }
  265.       thingToAddToMenu = (isReqd == "N" && newChk == "")?"":isReqd+newChk; //concat R/N and check
  266.       addValueToMenuItem(document.theForm.fieldMenu, curFieldNum, thingToAddToMenu);
  267.       document.theForm.fieldMenu.selectedIndex = curFieldNum; //reset selection index
  268.     } else alert(MSG_NoSelection);
  269. }
  270.  
  271.  
  272.  
  273. //if the Range radio btn is not checked, do nothing
  274. //else if either entry is not a number, do nothing
  275. //else if a < b, construct range string
  276. //else give error
  277.  
  278. function saveRangeToMenu(newChk,fromRadio){
  279.   var fromNum,toNum,i,theRadio,rangeStr;
  280.  
  281.   if (document.theForm.theCheck[3].checked) { //if the radio is checked
  282.     fromNum = parseFloat(document.theForm.fromNum.value); //get from number
  283.     toNum = parseFloat(document.theForm.toNum.value); //get to number
  284.     if (!isNaN(fromNum) && !isNaN(toNum)) { //if valid numbers
  285.       if (fromNum <= toNum) {
  286.         rangeStr = newChk + fromNum + ":" + toNum;
  287.         saveCheckToMenu(rangeStr);
  288.       } else {
  289.         saveCheckToMenu('');
  290.         if (fromRadio) alert(MSG_InvalidRange);
  291.       }
  292.     } else saveCheckToMenu('');
  293.   }
  294. }
  295.