/* File 06.js - library of simple validation functions
        This library uses Regular Expressions for pattern matching.
        See isValidEmail() for example.
   last updated November 15, 1999
   Usage: in the <HEAD> section of your HTML document
   <SCRIPT LANGUAGE="JavaScript" SRC="06.js">

     document.write("warning - unable to locate included 'js' file")
   

</SCRIPT>
   WARNING - WARNING - WARNING - WARNING - WARNING 
   It is essential that all validation functions
        return 'false' if the test fails  (yields undesirable results)
        return 'true'  if the test passes (yields the desired results)
   ===================================================================
   This library is used updated versions of the validation functions
   that rely on receiving objects, and uses the properties of the objects
   such as .value, .name, form 
   ... description ends and the useful part of the file begins ...      
*/
<!-- the following will be invisible to browsers that do not support JavaScript

//==============================================================
// Function: isNotBlank
// Purpose:  to check the the input is NOT blank
// general purpose function to see if an input value has been entered at all
//      returns false if the input IS blank
//      usage: <INPUT NAME="someField" VALUE="someValue" onChange="isNotBlank(this)">
//      this function superceds isBlank() included at the end of this file
//      for reference (better logic and consistent language)
//       - desired result returns true
//       - undesired result returns false
// general purpose function to see if an input value has been entered at all
function isNotBlank(obj) {
    var str     = obj.value ; // value to be 'tested' 
    var name    = obj.name  ; // name of the field      
    var errMsg  = "Please enter something for " +name + ".\n Required entry"
    if (str == "" || str == null) {
        alert(errMsg) ; // tell the user what is wrong
        obj.focus()   ; // focus on the field with the problem
        obj.select()  ; // select the contents of the field with the problem
        return false  ; // tell wrap around function that this value fails
    }
    return true       ; // tell wrap around function that this value passes
}
//==============================================================
// Function: isNumRange
// Purpose: to check that input is within the not blank, and is numeric
//          and withing a specified range
// Usage: <INPUT NAME="someField" VALUE="someValue" onChange="isNumRange(this,0,300)">
//      this assumes that minimum acceptable is 0 and maximum acceptable is 300
function isNumRange(obj, min, max){
    var str     = obj.value ; // value to be 'tested' 
    var name    = obj.name  ; // name of the field      
    var errMsg  = "Please enter a number between " + min + " and "+ max
        errMsg +="\nfor " + name + ". (Required entry)" ;
        errMsg +="\nYou entered \"" + str +"\"." ;
// check for blank field
        if (str==""){
          alert(errMsg) ; // tell the user what is wrong
          obj.focus()   ; // focus on the field with the problem
          obj.select()  ; // select the contents of the field with the problem
          return false  ; // tell wrap around function that this value fails
        }
// check for non-digits
        for (var i=0; i < str.length; i++){  
        var ch = str.charAt(i)
        if (ch < "0" || ch > "9"){       
         alert(errMsg) ; // tell the user what is wrong
          obj.focus()   ; // focus on the field with the problem
          obj.select()  ; // select the contents of the field with the problem
          return false  ; // tell wrap around function that this value fails
         }
        }
// check if within range 
        var val = parseInt(str, 10)
        if ((val < min) || (val > max)) {
          alert(errMsg) ; // tell the user what is wrong
          obj.focus()   ; // focus on the field with the problem
          obj.select()  ; // select the contents of the field with the problem
          return false  ; // tell wrap around function that this value fails
         }
    return true         ; // tell wrap around function that this value passes
}

//=========================================================
// Function: isValidEmail(obj)
// Description : Checks if given email address has valid syntax
// usage: <INPUT TYPE="TEXT" NAME="e-mail" onChange="isValidEmail(this)" >
// note: Validation assumptions 
//   E-mail address has an "@" symbol in it. 
//     and at least one alphanumeric character before the "@" symbol. 
//     and either a two-letter country code or a .com, .net, .edu, .mil, .gov or .org suffix 

function isValidEmail (obj){
    var str     = obj.value ; // value to be 'tested' 
    var name    = obj.name  ; // name of the field      
    var errMsg  = "Please enter your valid email address." 
          errMsg +="\nfor " + name + ". (Required entry)" ;
          errMsg +="\nYou entered \"" + str +"\"." ;              


   var newString = str.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
   if (!newString){  
        alert(errMsg) ; // tell the user what is wrong
        obj.focus()   ; // focus on the field with the problem
                obj.select()  ; // select the contents of the field with the problem
                return false  ; // tell wrap around function that this value fails
   }
    return true     ; // tell wrap around function that this value passes
}

// === documentation for new version of isValidEmail =====
/*      comments to explain the new version - 
        in a production environment you can remove all
   of the comments as the functional part follows 
        The next 2 lines using a regular expression  
        replace the 9 that follow them
------- new code using a regular expression ------------
   var newString = str.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
   if (!newString){  
------- this (down to the next dotted line -------------
        var atSign      = str.indexOf('@')      //locate position of '@' sign
        var dot                         = str.lastIndexOf('.')  // locate position of dot
        var blank       = str.indexOf(' ')      // locate position of blanks (shouldn't be any)
        var length      = str.length - 1        // define array is from 0 to length-1
if ((atSign < 1)      ||   // '@' must not be first character
    (dot <= atSign+1) ||   // must be at least one valid character between '@' and '.'
    (dot == length)   ||   // is the dot the last character (not valid if true)
    (blank  != -1)         // No empty spaces permitted
   ){
--------------------------------------------------------   
Notes about the regular expression:
/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi
/       =begin regular expression
\b =word boundary 
^       =beginning of the string
\S      =no spaces
+@      =contains an @ sign
(\.com)|(\.net)|(\.edu) = list of endings acceptable done with $)\b
/gi=global, case insensitive
see:
http://developer.netscape.com:80/viewsource/angus_strings.html 
http://developer.netscape.com:80/docs/manuals/communicator/jsguide/regexp.htm
*/

//=========================================================
// Function: isValidPhone(obj)
// Description : verifies that obj.value is a telephone
// number (ten digits - with or without parentheses and dashes)
// usage: <INPUT TYPE="TEXT" NAME="Telephone" onChange="isValidPhone(this)" >
// 
function isValidPhone(obj) {
         var re = /\(?\d{3}\)?([-\/\.\s])\d{3}[\1-]\d{4}/
    var str     = obj.value ; // value to be 'tested'
    RegExp.input =str      ; // aka RegExp.input
    var name    = obj.name  ; // name of the field      
    var errMsg  = "Please enter your Telephone Number." 
          errMsg +="\nin  " + name + ". (Required entry)" ;
          errMsg +="\nYou entered \"" + str +"\"." ;              
          errMsg +="\ntry a pattern like " ;
          errMsg +="\n(999) 999-9999 or 999.999.9999";            
   OK = re.exec()                       ; // assign outcome exec method to OK
   if (!OK){                    ; // if not OK then the test fails
        alert(errMsg)   ; // tell the user what is wrong
                obj.focus()     ; // focus on the field with the problem
                        obj.select()    ; // select the contents of the field with the problem
                        return false    ; // tell wrap around function that this value fails
           }
            return true     ; // tell wrap around function that this value passes
        }

/*      The regular expression looks for zero or one open parenthesis \(?, 
        followed by three digits \d{3}, followed by zero or one close
        parenthesis \)?, followed by one dash, forward slash, decimal point
        or space 
        and when found, remember the character ([-\/\.\s]), followed by
        three digits \d{3}, followed by the a dash or remembered match of a dash, 
        forward slash, decimal point or space \1, followed by four digits \d{4}. 
*/      


//=========================================================
// Function: isSelectedRange(obj,min,max)
// Description : Checks if number of items selected is within a range 
// usage: <SELECT NAME="Fruit" onChange="isSelectedRange(this,1,3)" >
// obj.length is the number options
// obj.options.[i].selected is the state of option[i] in obj
function isSelectedRange(obj,min,max){
        var name        = obj.name  ; // name of the field      
        var errMsg      = "Please select between " + min + " and " + max + " items" 
         errMsg += "\nfor  " + name + "." ;
                var selectedCount=0
   for (var i=0; i < obj.options.length; i++) {
      if (obj.options[i].selected==true)
         selectedCount++
   }
        // alert(selectedCount + " items selected")
        if (selectedCount < min || selectedCount > max )
        {
        errMsg += "\nYou have selected " + selectedCount + " item(s)." ;
        alert(errMsg) ; // tell the user what is wrong
        obj.focus()   ; // focus on the field with the problem
                obj.select()  ; // select the contents of the field with the problem
                return false  ; // tell wrap around function that this value fails
   }
    return true     ; // tell wrap around function that this value passes
}

//=========================================================
// Function: isSelected(obj)
// Description : Checks if number of items selected is within a range 
// usage: <SELECT NAME="Fruit" onChange="isSelected(this)" >
// this one is tricky as we have to cycle through all the options
// checking to see if something is selected, 
// and then if it is, we can read the value and if that is null
// then we know that the default selection (which should have
// a null ("") value is selected i.e. our user has made no
// selection.
// obj.length is the number options
// obj.options.[i].selected is the state of option[i] in obj
function isSelected(obj){
        var name        = obj.name  ; // name of the field      
        var testValue = false  ; // flag
        var errMsg      = "Please select something from the list for" 
         errMsg += "\n  " + name + "." ;
                var selectedCount=0
   for (var i=0; i < obj.options.length; i++) {
      if (obj[i].selected){
           if(obj[i].value != ""){
                        testValue=true                          }
                }       
   }
        // alert(selectedCount + " items selected")
        if (testValue==false){
                errMsg += "\nYou have selected " + selectedCount + " item(s)." ;
                alert(errMsg) ; // tell the user what is wrong
                obj.focus()   ; // focus on the field with the problem
                        obj.select()  ; // select the contents of the field with the problem
                        return false  ; // tell wrap around function that this value fails
   }
    return true     ; // tell wrap around function that this value passes
}

//=========================================================
// Function: isPasswordOk(obj)
// Description : Uses JavaScript prompt to verify original password entry
// usage: <INPUT TYPE="PASSWORD" NAME="Password" onChange="isPasswordOk(this)" >
//
function isPasswordOk(obj){
var str = obj.value
        var errMsg      = "Your confirmation did not match!" ;
         errMsg += "\nPlease try again." ;

var checkWord = ""
checkWord = prompt("Please re-enter your password",checkWord);
if (str !=checkWord){
        alert(errMsg) ; // tell the user what is wrong
        obj.focus()   ; // focus on the field with the problem
                obj.select()  ; // select the contents of the field with the problem
                return false  ; // tell wrap around function that this value fails
   }
    return true     ; // tell wrap around function that this value passes
}
//=========================================================
// Function: isCheckedBox
//      Purpose:        Is the checkbox checked?
function isCheckedBox(obj){
        var str         = obj.value ; // value to be 'tested' 
        var name        = obj.name  ; // name of the field      
        var checked= obj.checked; // status (t/f) of checked property
        var errMsg      = "Please pick one of the options" 
                errMsg +="\nfor " + name + ". (Required entry)" ;
        if (obj.checked == false){
                alert(errMsg)
        obj.focus()   ; // focus on the field with the problem
//              obj.select()  ; // select the contents of the field with the problem

                return false
                }
        return true
        alert("isChecked = "+checked)
}

//=========================================================
// Function: isCheckedRadio
//      Purpose:        Is one of the radio buttons checked?
function isCheckedRadio(obj){
        var str         = obj.value ; // value to be 'tested' 
        var checked= ""      ; // initialize
        var name = obj[0].name ; // get the name (this is an array)
        var errMsg      = "Please pick one of the options for" 
                errMsg +="\n" + name + ". (Required entry)" ;
                
        for (var i in obj) {
      if (obj[i].checked=="1") {
         checked =obj[i].value  ; 
         }
        }       
        if (checked == ""){
                alert(errMsg)
        obj[0].focus()   ; // focus on the field with the problem
                obj[0].select()  ; // select the contents of the field with the problem
                return false
                }
        return true
        alert("isChecked = "+checked)
}




//==================================================
//============= Superceded Functions ===============
//==================================================
// Function: isBlank
// Purpose:  to check the the input is NOT blank
//      returns false if the input IS blank
//      usage: <INPUT NAME="someField" VALUE="someValue" onChange="isBlank(this.value)">
function isBlank(str)
{
// check for blank field
        if (str=="")  
        {
        alert("Please enter a city in the box")
        return false
        }
        return true
}
//==============================================================
// Function: isNumRange
// Purpose: to check that input is within the not blank, and is numeric
//          and withing a specified range
// Usage: <INPUT NAME="someField" VALUE="someValue" onChange="isNumRange(this.value)">
function isNumRangeOld(str, min, max)
{
// check for blank field
        if (str=="")  
        {
        alert("Please enter a number between " + min + " and " + max +" in the box")
        return false
        }
// check for non-digits
        for (var i=0; i < str.length; i++)  
        {
        var ch = str.charAt(i)
                if (ch < "0" || ch > "9")       
                {
                        alert("Only digits 0-9 are allowed")
                        return false
                }
        }
// check if within range 
        var val = parseInt(str, 10)
        if ((val < min) || (val > max))  
        {
                alert("You entered " + val + ". Valid scores are from " + min + " to " + max +". Please try again")
                return false
        }
                return true
}

//=== end of functions used in Form examples ==============
//=== some other validation functions you might find useful
//=========================================================

// whitespace characters
var whitespace = " \t\n\r ";

// Removes all characters which appear in string bag from string s.
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: stripWhiteSpace
// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}
//=========================================================
// Example
function isValidInput(str)
{
// check for blank field
        if (str=="")  
        {
        alert("Please enter a value in the field")
        return false
        }
        return true
}



//==============================================================
// Function: promptEntry
// Purpose:  to display a prompt on the status bar
// Usage: <INPUT NAME="someField" ... onFocus="promptEntry('enter your age in years')">
function promptEntry (s)
{   window.status =  s
}



// end hiding from older browsers   -->

