﻿// validation.js
// -------------
// Provides functions useful in form validation. 


// Returns true if the given field contains non-whitespace text. If not, an 
// alert pops up, focus is set to that field, and the function returns false. 
// 
//   fieldName: target field's 'name' attribute
//   friendlyName: field name to show in the alert box

function ValidateNonEmpty( fieldName, friendlyName ) {

    // Locate the given field
    var targetField = null;
    var matchingFields = document.getElementsByName( fieldName );
    if ( matchingFields.length > 0 ) {
        targetField = matchingFields[ 0 ];
    }
    
    // Show an error if the field doesn't exist
    if ( !targetField ) {
        alert( 'Internal Error: Field "' + fieldName + '" does not exist.' );
        return false;
    }
    
    // If the field has a value, return true
    var fieldValue = GetFieldValue( targetField );
    if ( fieldValue != '' ) {
        return true;
    }
    // Otherwise, if the field is empty...
    else {
    
        // Show the validation alert
        alert( 'Please complete the ' + friendlyName + ' field.' );
        
        // Set focus to the field
        targetField.focus();
        
        // Return false
        return false;
    }
    
} // end ValidateNonEmpty()



// Returns the value of the given field. If the field is a <select> box, the 
// first option is assumed to mean 'not selected'.
function GetFieldValue( field ) {
    
    // Assume value is blank
    var fieldValue = '';
    
    // If this is a select box...
    if ( field.options ) {
        
        // Use the option's value or text, whichever is available
        var optionValue = field.options[ field.selectedIndex ].value;
        var optionText = field.options[ field.selectedIndex ].text;
        if ( optionValue != '' ) {
            fieldValue = optionValue;
        }
        else {
            fieldValue = optionText;
        }
        
        // If the first option is selected, assume its value to be blank
        if ( field.selectedIndex == 0 ) {
            fieldValue = '';
        }
    }
    // Otherwise, assume this is a text field and use its text value
    else {
        fieldValue = field.value;
    }
    
    // Return the result
    return fieldValue;
    
} // end GetFieldValue() 



// TrimString(): Trims whitespace from the beginning and end of 
// the given string.
function TrimString( sourceString ) {
    var result = sourceString.replace( /^\s+/, '' );
    result = result.replace( /\s+$/, '' );
    return result;
}
