Solved

Form validation using Javascript in JSP language without using JSP property

Posted on 2004-04-06
14
720 Views
Last Modified: 2010-08-05
Hi, i'm new to jsp and javascript and currently i'm having problems doing the validation for the fields in my form. Hope that someone can help me to solve my problem asap. thanx.

I've a form named AddEmp and the action="EmpAdd.jsp" which include the following fields:
EmpNo (a 4 digit number)
EmpPIN (a 4 digit number)
EmpName, EmpIC, EmpAdd, EmpContact (all strings)
Department (a dropdown list)
A submit and reset image button

I wish to get help in typing the coding to check if the EmpNo & EmpPIN is a 4 digit number, to check if the strings are all filled in and does the user select a department.

I don't mind using alert to display the message and if all the fields met the requirement, will the form proceed to EmpAdd.jsp?

I've searched on the net and found many different ways of doing it. but I don't understand what is it about. Hope to find a easy way out to do the validation. Can it be done by adding the Javascript coding above the form in the same JSP page?
0
Comment
Question by:gilliam_ang
  • 6
  • 5
  • 3
14 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 10772199
You can call a Javascript function onSubmit of the form, like:

<FORM name="AddEmp" action="EmpAdd.jsp" OnSubmit="return validations ();">

In the function validations (), you can do the various validations and if something is wrong, display an alert and return false, else return true.
0
 
LVL 6

Expert Comment

by:jarasa
ID: 10773180
Hi, two things:

1.- Wich browser do you use, or could be anyone?
2.- If you post you code I'll be able to make the proper change on it and explain them to you

Javier

0
 
LVL 6

Assisted Solution

by:jarasa
jarasa earned 35 total points
ID: 10773251
Anyway as mayankeagle you should make it on a JavaScript Fuction take a look at this example and try to work around it, it will be better for you than if I make your code:

:c)

<html>
<head>
<script>

 function average(myform)
 {
  myform.answer.value = (parseInt(myform.num1.value) +
                         parseInt(myform.num2.value) +
                         parseInt(myform.num3.value)) / 3;
 }

 function findsum(total)
 {
  total.sum.value =  (parseInt(total.num1.value) +
                         parseInt(total.num2.value) +
                         parseInt(total.num3.value));
 }

function checkEmpty() {

      if (document.thisform.num1.value!="")
            if (document.thisform.num2.value!="")
                  if (document.thisform.num3.value!=""){
                        document.thisform.button1.disabled=false;
                        document.thisform.button2.disabled=false;
                        document.thisform.button3.disabled=false;
                  }
                        
}

function checkDigit(field) {
      
      var c = field.value;
      var d = "";
      
      for (x=0; x<c.length; x++) {
            if (isDigit(c.substring(x,x+1))){

                  d = d + c.substring(x,x+1);

            } else {

                  break;

            }
      }
      field.value=d;
      return;
        
}

function isDigit(c) {
      return ((c >= "0") && (c <= "9"))
}
</script>
</head>

<body>
<p>


<form name=thisform>

      Enter first number: <input onkeyup="checkDigit(this);" type=text name=num1 onBlur="checkEmpty();">
 <br> Enter second number: <input onKeyup="checkDigit(this);" type=text name=num2 onBlur="checkEmpty();">
 <br> Pick third number: <select name=num3 onBlur="checkEmpty();">
                                     <Option value=''></option>
                                     <Option value=1>1</option>
                                     <Option value=2>2</option>
                                     <Option value=3>3</option>
                                     <Option value=4>4</option>
                                     </select>
 <br> Total   is: <input readonly type=text name=sum size=6>
 <br> Average is: <input readonly type=text name=answer size=6>
 <p>
 
 <input disabled name=button1 type=button value="Get All" onClick="average(thisform);findsum(thisform);">
 <input disabled name=button2 type=button value="Get Average" onClick="average(thisform);">
 <input disabled name=button3 type=button value="Get Total  " onClick="findsum(thisform);">
 <input type="reset" value="Reset!" onClick="document.thisform.button1.disabled=true;document.thisform.button2.disabled=true;document.thisform.button3.disabled=true;">



</form>
</body>
</html>

Javier

0
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
LVL 6

Expert Comment

by:jarasa
ID: 10773299
I forgot about the length of the fields change this:

function checkDigit(field) {
      
      var c = field.value;
      var d = "";
      
      for (x=0; x<c.length; x++) {
            if (isDigit(c.substring(x,x+1))){
                  if(d.length>3){
                        break;
                  } else {
                        d = d + c.substring(x,x+1);
                  }
            } else {

                  break;

            }
      }
      field.value=d;
      return;
        
}


and this too:

 <br> Pick third number: <select name=num3 onBlur="checkEmpty();" onchange="checkEmpty();">


Javier
0
 

Author Comment

by:gilliam_ang
ID: 10780444
If I use the checkEmpty(), checkDigit(field) and isDigit(c) function, How do I alert the user to prompt them to enter a value for the field?

this is the javascript part which I've took from Javier.
<script language="Javascript">
function checkEmpty() {

     if (document.AddEmp.EmpName.value!="")
          if (document.AddEmp.EmpIC.value!="")
               if (document.AddEmp.EmpAdd.value!="")
                   if (document.AddEmp.EmpContact.value!="")
            if (document.AddEmp.Department.value!="")
                if (document.AddEmp.Designation.value!=""){
                  alert("Please fill in all the fields.");
                                       return false;
                              }                    
}

function checkDigit(field) {
     
     var c = field.value;
     var d = "";
     
     for (x=0; x<c.length; x++) {
          if (isDigit(c.substring(x,x+1))){
               if(d.length>3){
                    break;
               } else {
                    d = d + c.substring(x,x+1);
               }
          } else {

               break;

          }
     }
     field.value=d;
     return;    
}

function isDigit(c) {
     return ((c >= "0") && (c <= "9"))
}

</script>

 and this is my form:
            <form method="post" name="AddEmp" action="AddEmp.jsp">
              <table align="center">
                <tr class="form">
                  <td>Employee No. :</td>
                  <td><input type="text" name="EmpNo" size="4" maxlength="4" onBlur="checkDigit(this);" >&nbsp;(a 4-digit number)</td>
                </tr>
                <tr class="form">
                  <td>PIN No. :</td>
                  <td><input type="text" name="EmpPIN" size="4" maxlength="4" onBlur=="checkDigit(this);" >&nbsp;(a 4-digit number)</td>
                </tr>
                <tr class="form">
                  <td>Name :</td>
                  <td><input type="text" name="EmpName" onBlur="checkEmpty();"></td>
                </tr>
                <tr class="form">
                  <td>IC No. :</td>
                  <td><input type="text" name="EmpIC" onBlur="checkEmpty();"></td>
                </tr>
                <tr class="form">
                  <td>Address :</td>
                  <td><input type="text" name="EmpAdd" size="50" onBlur="checkEmpty();"></td>
                </tr>
                <tr class="form">
                  <td>Contact No. :</td>
                  <td><input type="text" name="EmpContact" onBlur="checkEmpty();"></td>
                </tr>
                <tr class="form">
                  <td>Department :</td>
                  <td><select name="Department" onBlur="checkEmpty();" onchange="checkEmpty();">
                      <option selected>&nbsp;</option>
                      <option value="IT">IT</option>
                      <option value="HR">HR</option>
                      <option value="Production">Production</option>
                    </select></td>
                </tr>
                <tr class="form">
                  <td>Designation :</td>
                  <td><select name="Designation" onBlur="checkEmpty();" onchange="checkEmpty();">
                      <option selected>&nbsp;</option>
                                <option value="--">--</option>
                      <option value="Supervisor">Supervisor</option>
                    </select></td>
                </tr>
                <tr>
                  <td><input name="Add" type="image" id="Submit" src="../firework/button/Submit/Add.gif" alt="Add" width="116" height="20" border="0" onclick="return validate()"></td>
                  <td><input type="image" src="../firework/button/Submit/Clear.gif" alt="Clear" name="Clear" width="116" height="20" border="0" onclick="javascript:reset();return false;"></td>
                </tr>
              </table>
            </form>

Don't mind help me check if there's anything wrong with my coding. Thanks very much.
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 40 total points
ID: 10780735
The checkEmpty () function seems to be reversed ;-)

You need: if ( document.AddEmp.EmpName.value == "" ) instead of: >> if (document.AddEmp.EmpName.value!="")

and so on.... - then the alert would work if all fields are blank.
0
 

Author Comment

by:gilliam_ang
ID: 10781117
okay... so the rest of the function are correctly used?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10781191
Well, I don't think that the checkEmpty () function should be called on-blur of the text in every text-field. Maybe that you can call it on click of the submit-button. Because here, even if you fill something in a text-field and are about to fill something in another text-field, it could be fired and it would say that you have to enter something in the other text-field (which you are about to do anyway).
0
 

Author Comment

by:gilliam_ang
ID: 10781675
where to include the alert for the checkDigit function? it doesn't seem to work. when i leave all the fields blank, it will still submit to the action page without checking the validation. Please help.
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 40 total points
ID: 10781707
Try calling "return checkEmpty ();" in the OnSubmit of the form. Write the function like this:

function checkEmpty ()
{
  if ( Trim ( if ( document.AddEmp.EmpName.value ) =="" )
  {
    alert ( "Please enter the employee-name. " ) ;
    return false ;

  }

  // same-way for other fields

  return true ;

}
0
 

Author Comment

by:gilliam_ang
ID: 10781747
How to check if a drop down list is empty or selected?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10781756
Same method. if ( document.AddEmp.dropDownListName.value == "" )
0
 

Author Comment

by:gilliam_ang
ID: 10799739
How can i make sure that the user had enter a 4 digit number in the EmpNo and EmpPIN field? Since EmpContact is also using the same function as EmpNo and EmpPIN, does i need to rename another set of function for EmpContact as EmpContact is not just 4 digit number. Please help asap cause i have wasted most of my time on this validation and i stil have many parts of the project not done yet and the due date is near. this is my codes:

<script language="Javascript">
<!--
function validRequired(formField,fieldLabel)
{
      var result = true;
      
      if (formField.value == "")
      {
            alert('Please enter a value for the "' + fieldLabel +'" field.');
            formField.focus();
            result = false;
      }
      
      return result;
}

function allDigits(str)
{
      return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
      var result = true;

      // Note: doesn't use regular expressions to avoid early Mac browser bugs      
      for (var i=0;i<str.length;i++)
            if (charset.indexOf(str.substr(i,1))<0)
            {
                  result = false;
                  break;
            }
      
      return result;
}

function validNum(formField,fieldLabel,required)
{
      var result = true;

      if (required && !validRequired(formField,fieldLabel))
            result = false;
 
       if (result)
       {
             if (!allDigits(formField.value))
             {
                   alert('Please enter a number for the "' + fieldLabel +'" field.');
                  formField.focus();            
                  result = false;
            }
      }
      
      return result;
}

function validInt(formField,fieldLabel,required)
{
      var result = true;

      if (required && !validRequired(formField,fieldLabel))
            result = false;
 
       if (result)
       {
             var num = parseInt(formField.value,10);
             if (isNaN(num))
             {
                   alert('Please enter a number for the "' + fieldLabel +'" field.');
                  formField.focus();            
                  result = false;
            }
      }
      
      return result;
}

function checkDropdown(formField, fieldLabel)
{
 if(formField.options[formField.selectedIndex].value == ""
 || formField.options[formField.selectedIndex].value == "NULL")
 {
  alert(fieldLabel);
  formField.focus();
  return false;
 }
 return true;
}

function validateForm(theForm)
{
      // Customize these calls for your form

      // Start ------->
      if (!validNum(theForm.EmpNo,"Employee No.",true))
            return false;
            
      if (!validNum(theForm.EmpPIN,"PIN No.",true))
            return false;
            
      if (!validRequired(theForm.EmpName,"Name"))
            return false;

      if (!validRequired(theForm.EmpIC,"IC No."))
            return false;

      if (!validRequired(theForm.EmpAdd,"Address"))
            return false;
            
      if (!validNum(theForm.EmpContact,"Contact No.",true))
            return false;
            
      if (!checkDropdown(theForm.Department,"Please choose one department."))
            return false;
            
      if (!checkDropdown(theForm.Designation,"Please choose one selection for the position."))
            return false;
      // <--------- End
      
      return true;
}
//-->
</script>

<form action="AddEmp.jsp" method="post" name="AddEmp" onsubmit="return validateForm(this)">
<table><tr class="form">
                  <td>Employee No. :</td>
                  <td><input type="text" name="EmpNo" size="4" maxlength="4">&nbsp;(a 4-digit number)</td>
                </tr>
                <tr class="form">
                  <td>PIN No. :</td>
                  <td><input type="text" name="EmpPIN" size="4" maxlength="4">&nbsp;(a 4-digit number)</td>
                </tr>
                <tr class="form">
                  <td>Name :</td>
                  <td><input type="text" name="EmpName"></td>
                </tr>
                <tr class="form">
                  <td>IC No. :</td>
                  <td><input type="text" name="EmpIC"></td>
                </tr>
                <tr class="form">
                  <td>Address :</td>
                  <td><input type="text" name="EmpAdd" size="50"></td>
                </tr>
                <tr class="form">
                  <td>Contact No. :</td>
                  <td><input type="text" name="EmpContact"></td>
                </tr>
                <tr class="form">
                  <td>Department :</td>
                  <td><select name="Department">
                      <option selected></option>
                      <option value="IT">IT</option>
                      <option value="HR">HR</option>
                      <option value="Production">Production</option>
                    </select></td>
                </tr>
                <tr class="form">
                  <td>Designation :</td>
                  <td><select name="Designation">
                      <option selected></option>
                                <option value="--">--</option>
                      <option value="Supervisor">Supervisor</option>
                    </select></td>
                </tr>
                <tr>
                  <td><input name="Add" type="image" id="Submit" src="../firework/button/Submit/Add.gif" alt="Add" width="116" height="20" border="0" onclick="return validate()"></td>
                  <td><input type="image" src="../firework/button/Submit/Clear.gif" alt="Clear" name="Clear" width="116" height="20" border="0" onclick="javascript:reset();return false;"></td>
                </tr>
              </table>
            </form>
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10803820
Your validInt () function should probably take an argument as length, which will tell what should be the maximum length or exact length of the field (whichever way you want to interpret it). For Emp No, it will be 4, and so on.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
library class in java 1 92
unit test DAO layer 1 137
maven project in eclipse 11 59
HTTPSessionBindingListernter not configured in deployment descriptor 2 53
How do we balance the user experience (UX) with reasonable security measures? It can be done, if you keep these fundamentals in mind.
Knowing where your website is hosted is as important as the features you receive, the monthly fee, and the support you receive. Due diligence should be done when choosing your next hosting provider.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question