Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Combining functions

Status
Not open for further replies.

jbunn555

Technical User
Oct 15, 2006
5
US
Hi everyone does anybody know how to combine 2 seperate functions. Here is my first function code:
function formcheck(formobj){
// Enter name of mandatory fields
var fieldRequired = Array("name", "email", "comment");
// Enter field description to appear in the dialog box
var fieldDescription = Array("Name", "Email", "Comment");
// dialog message
var alertMsg = "Please complete the following fields:\n";

var l_Msg = alertMsg.length;

for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired];
if (obj){
switch(obj.type){
case "select-one":
if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription + "\n";
}
break;
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription + "\n";
}
break;
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription + "\n";
}
break;
default:
}
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
}
}
if (!blnchecked){
alertMsg += " - " + fieldDescription + "\n";
}
}
}
}

if (alertMsg.length == l_Msg){
return true;
}else{
alert(alertMsg);
return false;
}
}
// -->
</script>

I want to combine a script for email checking to make sure there is a @ sign and a "." and does not contain special characters.
 
Just call the second function from the first. In this particular case I would add an array:
Code:
var fieldCheck = Array(undef, check_email, undef);
alongside fieldRequired and fieldDescription (where check_email is the name of your email-checking function), and then add:
Code:
if (fieldCheck[i] != undefined) { fieldCheck[i](obj); }
inside the if (obj){ block that you have. But that's more complex than you might need.
 
I need to combine this into my function so that onclick will do all that i need which is the function i posted plus this:
<script language = "Javascript">
/**
* DHTML email validation script. Courtesy of SmartWebby.com ( */

function echeck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}

if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}

if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}

if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}

return true
}

function ValidateForm(){
var emailID=document.frmSample.txtEmail

if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
</script>
 
jbunn555, that second function looks a bit overly complex.
Here is what I use to validate email:
Code:
function email(value) {
  //Requires minimum two characters before @, two chars after and two chars after.
  var re = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
  return re.test(value);
}

You just pass in the value and it returns true or false.

So to integrate it into your function you would do something like this:
Code:
  case "text":
    if (email(obj.value)) {
      alertMsg += " - " + fieldDescription[i] + "\n";
    }
  break;

Did you write the first function or are you trying to modify code from elsewhere?

It is a nice approach to loop through the form elements testing each one but you are limited with the rest of your approach in that you only have one type of test for each type of field on your form. If you had several text fields they would ALL be tested with the email function.
You could use the case to check for field type and then use multiple if statements to test the name or ID of the field and then apply a specific test but you would have to specify every field on the form and each test that should be applied to it.

Another approach could be to modify your array to have another dimension so that you would have the name of the field as the top element in that array position and have it followed by each type of validation to perform. With this approach you would not have to test field type since you would be directly stating which type of validation to perform for each field on the page anyway.

This way the validation routine can work more flexibly with all of your other forms in the future without having to make your code extremely long or highly customized for each page.

In my own validation code I setup custom tags for each field to be validated and I read those tags in when I run my validation function rather than building an array manually in the code.
For example.
Code:
<form name="myform" id="myform" action="" method="post" onsubmit="return getValidationInfo(myform)">
  <span id="dFirst">First Field: </span><input type="text" name="First" id="First" readOnly> Whole positive number <br>
<!--
  for="First" 
  validator="6" 
  clrchg="dFirst" 
  errorMsg="First field" 
-->
  <span id="dSecond">Second Field:</span> <input type="text" name="Second" id="Second"> Whole positive number<br>
<!--
	validator="6"
	for="Second"
	errorMsg="Second field"
 -->
  <span id="dThird">Third Field:</span> <input type="text" name="Third" id="Third" validator="5" clrchg="dThird"> Alpha/Numeric including . ' - _<br>
<!--
	for="Third"
        validator="5"
	errorMsg="Three to five letters beginning with capital \"C\", please."
 -->
  <br>
  <input type="submit" name="Submit" value="Submit"><br><br>
</form>

See how I have setup a for, validator and errorMsg value within comment tags for each field?
I loop through the form checking each form element and if it has associated comment tags then use that information to know how to validate that field and what error message to display.
In my case I am using numbers to indicate which type of validation to perform and a case statement that calls the associated functions.

There are lots of approaches. It just looks as if you are trying to come up with a more sophisticated method so I thought I would throw a few ideas out there for your consideration.
I personally like to keep a library of validation routines that are very specific rather than writing a custom one for a specific need. For instance, instead of writing one routine to tell if a field is not blank, contains only upper case characters and is between 12 and 14 characters, I would use a not blank test, an uppercase only test and a length test. This way you have one library of routines you can re-use flexibly without customizing for every form you create. It just means that you apply multiple tests to a field rather than one single complex one that you have to write custom.

Good luck.

At my age I still learn something new every day, but I forget two others.
 
Wow that was very helpful thank you very much my only question is ok well the very first function from this thread needs to stay but i need to integrate just email checking, and your first suggestion of two before the @, two after, and two after the "." is exactly what i need but the thing is i'm not too familiar with javascript so could you maybe help me out with the integration of the:
case "text":
if (email(obj.value)) {
alertMsg += " - " + fieldDescription + "\n";
}
break;
into my current function to check my form by the way here is what my form looks like:
Note: all of the single quotes are actually supposed to be single quotes becuase i am calling it in php in an echo statement just to let you know that it is correct syntax.

<form action='contact.php' method='post' name='form' id='form' onSubmit='return customercomputersformcheck(this);'>
<table width='90%' border='0' cellspacing='2' cellpadding='4'>
<tr>
<td width='10%' align='right' valign='top'>Name:</td>
<td colspan='2' valign='top'><input name='name' type='text' id='name' size='30' />
</td>
</tr>
<tr>
<td width='10%' align='right' valign='top'>Email:</td>
<td colspan='2' valign='top'><input name='email' type='text' id='email' size='30' />
</td>
</tr>
<tr>
<td valign='top' align='right' width='10%'>Question:</td>
<td colspan='2' valign='top'><textarea name='question' cols='30' rows='5' id='question'></textarea>
</td>
</tr>
<tr>
<td width='10%' align='right'>&nbsp;</td>
<td colspan='2'><input type='submit' name='Submit' value='send' />
</td>
</tr>
</table>
</form>
 
In your current function you have a case statement
case "text":
But you have no code below it to go along with it.
You just replace that line with this code:
Code:
  case "text":
    if (!email(obj.value)) {
      alertMsg += " - " + fieldDescription[i] + "\n";
    }
  break;

Then you add the email function I posted above to your page.

When your code executes and it finds a text input field the case "text": section fires and calls the email function passing it the value of the field and getting back a true or false answer. If it returns false then the alertMsg is modified, if it returns true then it does nothing and continues checking other fields.



At my age I still learn something new every day, but I forget two others.
 
actually around the case text, it's saying "text" or "textarea" gets the code underneath textarea.
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription + "\n";
}
break;

so the code here is being performed for text and textarea is what's happening. so would i still just put your function and case text statement replacing my case text or do i need to do something else to make it all work together, and will replacing my case text make something that relies on that not work?
 
If you put in my code it contains a break statement that ends execution of the case "text" statement.

If you want to test text not to be blank you can add a line for that as well.
BTW, your form fields should never have a null value in them, they will be blank but not null so you do not need to test null.

There were a bunch of little problems in the code so rather than point them all out I just changed them.
Try something like this.
Code:
<script type="text/javascript">
function customercomputersformcheck(formobj) {
  // Enter name of mandatory fields
  var fieldRequired = Array("name", "email", "question");
  // Enter field description to appear in the dialog box
  var fieldDescription = Array("Name", "Email", "Comment");
  // dialog message
  var alertMsg = "Please complete the following fields:\n";
    
  var l_Msg = alertMsg.length;
    
  for (var i = 0; i < fieldRequired.length; i++) {
    var obj = formobj.elements[fieldRequired[i]];
    if (obj){
      switch(obj.type) {
        case "select-one":
          if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
            alertMsg += " - " + fieldDescription[i] + "\n";
          }
          break;
        case "select-multiple":
          if (obj.selectedIndex == -1){
            alertMsg += " - " + fieldDescription[i] + "\n";
          }
          break;
        case "text":
          if ((obj.name == "email" && !email(obj.value)) || obj.value == "") {
            alertMsg += " - " + fieldDescription[i] + "\n";
          }
          break;
        case "textarea":
          alert("Here");
          if (obj.value == ""){
            alertMsg += " - " + fieldDescription[i] + "\n";
          }
          break;
        default:
          if (obj.type == "undefined"){
            var blnchecked = false;
            for (var j = 0; j < obj.length; j++){
              if (obj[j].checked){
                blnchecked = true;
              }
            }
            if (!blnchecked){
              alertMsg += " - " + fieldDescription[i] + "\n";
            }
          }
      }
    }
  }     
  if (alertMsg.length == l_Msg){
    return true;
  }else{
    alert(alertMsg);
    return false;
  }
}

function email(value) {
  //Requires minimum two characters before @, two chars after and two chars after.
  var re = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
  return re.test(value);
}
</script>

You have TWO text fields though so the case statment for text had to be modified to detect if the field name was email and only call the email test function if it is. Otherwise your name field would insist on an email as well.


At my age I still learn something new every day, but I forget two others.
 
The code above did not work it did no checking at all just let me type something into one box and it was able to be submitted
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top