Solved

Javascript validation

Posted on 2004-10-31
1,031 Views
Last Modified: 2008-01-09
I need to modify the below javascript with the following conditions:

1. pUserName must be 5 characters and above (alphanumeric)
2. pPassword must be 5 characters and more(alphanumeric)
3. pName must be 5 characters and above (letters only, no digits)
4. pRegNo must be 7 digits
5. pICNo must be 12 digits
6. pContact must be 7 digits and above
7. pEmail must be an email address
8. pAccessLevel works fine.



<SCRIPT LANGUAGE="JavaScript">
<!--
pass = true ;

function IsEmptyField(strFieldName,strMessage){
var objFormField = document.forms[0].elements[strFieldName];
var strValue = objFormField.value;
strValue = strValue.split(" ").join("")
if(strValue.length<1){
     alert("The value for " + strMessage + " cannot be left blank!");
     objFormField.focus();
     pass = false;
      return pass;
}
pass = true;
      return pass;
}


function validForm(){
   if(!IsEmptyField('pUserName','User ID')){
                  pass = false;;
   }
   
else if(!IsEmptyField('pName','name')){
          pass = false;
   }

else    if(!IsEmptyField('pRegNo','Registration No')){
          pass = false;
   }
else    if(!IsEmptyField('pICNo','NRIC')){
          pass = false;
   }

     else  if(!IsEmptyField('pContact','Contact')){
          pass = false;
   }
else    if(!IsEmptyField('pEmail','Email')){
          pass = false;
   }

else if   (document.forms[0].pAccessLevel.value == '')
{
         alert("Access Level is a required field.");
          document.forms[0].pAccessLevel.focus();
          pass = false;

}
else if  ( (document.forms[0].pAccessLevel.value != 0 ) && (document.forms[0].pAccessLevel.value != 1 ) )
     {
          alert("Please Enter Your Access.");
          document.forms[0].pAccessLevel.focus();
          pass = false;

     }

     if (pass)
     {
          document.forms[0].action = "../admin/functions/fnc-listuser_datename.asp"
            document.forms[0].submit();
     }

}

//-->
</SCRIPT>
0
Question by:zamorin
    7 Comments
     
    LVL 3

    Expert Comment

    by:gnudiff
    For complex string checking the easiest way is to use regexps.

    Here is an example of how to check constraints you specified.

    Note, that a question of "valid" email address is not very clearly defined.

    Basically, here we assume that an email address may contain only:
    A-z - _ .  in the recipient part, and:
    A-z - _ in the domain parts, each part separatad by a "."
    and there should be one or more dot separated domain parts, and the last part should be 2-3 A-z characters only.

    So it would match:  my-user_one.two@this_is.a-domain.com

    but not: "a@b*zness.com" , nor "user@mydomain"

    Hope it helps, spent some time on it. :-i

    <html>
    <script>
    function validForm()
    {
          var frm=document.forms[0].elements;
          var errors = new Array();
          
          var rxUnamePass= new RegExp(/^[A-z0-9]{5,}$/);
          
          if (frm["pUserName"].value.search(rxUnamePass) == -1)
                errors.push("UserName must be 5 characters and above (alphanumeric)");
                
          if (frm["pPassword"].value.search(rxUnamePass) == -1)
                errors.push("Password must be 5 characters and above (alphanumeric)");
                
          if (frm["pName"].value.search(/^[A-z]{5,}$/) == -1)
                errors.push("Name must be 5 characters and above (letters only, no digits)");
          
          if (frm["pRegNo"].value.search(/^\d{7}$/) == -1)
                errors.push("RegNo must be 7 digits");

          if (frm["pICNo"].value.search(/^\d{12}$/) == -1)
                errors.push("ICNo must be 12 digits");
                
          if (frm["pContact"].value.search(/^\d{7,}$/) == -1)
                errors.push("Contact must be 7 digits and above");
                
          if (frm["pEmail"].value.search(/^[\w\-\.]+@([\w\-]+\.){1,}\w{2,3}$/) == -1)
                errors.push("Email does not seem to contain a valid email address");
          
          pass = (errors.length == 0);
          
          if (! pass)
                alert(errors.join("\n"));
                
    }
    </script>

    <form method="POST">
    <input type="text" name="pUserName" />1. pUserName must be 5 characters and above (alphanumeric)
    <br /><input type="text" name="pPassword" />2. pPassword must be 5 characters and more(alphanumeric)
    <br /><input type="text" name="pName" />3. pName must be 5 characters and above (letters only, no digits)
    <br /><input type="text" name="pRegNo" />4. pRegNo must be 7 digits
    <br /><input type="text" name="pICNo" />5. pICNo must be 12 digits
    <br /><input type="text" name="pContact" />6. pContact must be 7 digits and above
    <br /><input type="text" name="pEmail" />7. pEmail must be an email address
    <input type="button" onClick="return validForm()" value="Check" />
    </form>
    </html>
    0
     
    LVL 5

    Author Comment

    by:zamorin
    I've made the below code, but now the thing is there are 2 prompts that occurs cocurrently:

    ie: - It prompts me for the UserID and NRIC Number one after the other.


    <SCRIPT LANGUAGE="JavaScript">
    <!--
    pass = true ;

    function IsEmptyField(strFieldName,strMessage){
    var objFormField = document.forms[0].elements[strFieldName];
    var strValue = objFormField.value;
    strValue = strValue.split(" ").join("")
    if(strValue.length<1){
         alert("The value for " + strMessage + " cannot be left blank!");
         objFormField.focus();
         pass = false;
          return pass;
    }
    pass = true;
          return pass;
    }


    function validForm(){
    if(!IsEmptyField('pUserName','User ID')){
                      pass = false;
       }
    else if   (document.forms[0].pUserName.value.length < 5)
    {
             alert("Please enter atleast 5 character in the UserID field.");
              document.forms[0].pUserName.focus();
              pass = false;

    }
    else       if(!IsEmptyField('pPassword','Password')){
              pass = false;
       }
    else if   (document.forms[0].pPassword.value.length < 5)
    {
             alert("Please enter atleast 5 character in the Password field.");
              document.forms[0].pPassword.focus();
              pass = false;

    }
    else       if(!IsEmptyField('pName','name')){
              pass = false;
       }
    else if   (document.forms[0].pName.value.length < 5)
    {
             alert("Please enter atleast 5 character in the Name field.");
              document.forms[0].pName.focus();
              pass = false;

    }
    else    if(!IsEmptyField('pRegNo','Registration No')){
              return (false);
       }
    else if   (document.forms[0].pRegNo.value.length < 7)
    {
             alert("Please enter 7 digits in the Registration Number field.");
              document.forms[0].pRegNo.focus();
              return (false);
    }
      var checkOK = "0123456789-.";
      var checkStr = document.forms[0].pRegNo.value;
      var allValid = true;
      var validGroups = true;
      var decPoints = 0;
      var allNum = "";
      for (i = 0;  i < checkStr.length;  i++)
      {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
          if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length)
        {
          allValid = false;
          break;
        }
        if (ch == ".")
        {
          allNum += ".";
          decPoints++;
        }
        else
          allNum += ch;
      }
      if (!allValid)
      {
        alert("Please enter only digits in the \"Registration Number\" field.");
        document.forms[0].pRegNo.focus();
       return (false);
      }

    if (decPoints > 1 || !validGroups)
      {
        alert("Please enter a valid number in the \"Registration Number\" field.");
        document.forms[0].pRegNo.focus();
        return (false);
      }

    else if(!IsEmptyField('pICNo','NRIC Number')){
              return (false);
       }
    else if   (document.forms[0].pICNo.value.length < 12)
    {
             alert("Please enter 12 digits in the NRIC Number field.");
              document.forms[0].pICNo.focus();
              return (false);
    }
      var checkOK = "0123456789-.";
      var checkStr = document.forms[0].pICNo.value;
      var allValid = true;
      var validGroups = true;
      var decPoints = 0;
      var allNum = "";
      for (i = 0;  i < checkStr.length;  i++)
      {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
          if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length)
        {
          allValid = false;
          break;
        }
        if (ch == ".")
        {
          allNum += ".";
          decPoints++;
        }
        else
          allNum += ch;
      }
    if (!allValid)
      {
        alert("Please enter only digits in the \"NRIC Number\" field.");
        document.forms[0].pICNo.focus();
       return (false);
      }

    if (decPoints > 1 || !validGroups)
      {
        alert("Please enter a valid number in the \"NRIC Number\" field.");
        document.forms[0].pICNo.focus();
        return (false);
      }



    else    if(!IsEmptyField('pContact','Contact Number')){
              return (false);
       }
    else if   (document.forms[0].pContact.value.length < 7)
    {
             alert("Please enter at least 7 digits in the Contact Number field.");
              document.forms[0].pContact.focus();
              return (false);
    }
      var checkOK = "0123456789-.";
      var checkStr = document.forms[0].pContact.value;
      var allValid = true;
      var validGroups = true;
      var decPoints = 0;
      var allNum = "";
      for (i = 0;  i < checkStr.length;  i++)
      {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
          if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length)
        {
          allValid = false;
          break;
        }
        if (ch == ".")
        {
          allNum += ".";
          decPoints++;
        }
        else
          allNum += ch;
      }
      if (!allValid)
      {
        alert("Please enter only digits in the \"Contact Number\" field.");
        document.forms[0].pContact.focus();
       return (false);
      }

      if (decPoints > 1 || !validGroups)
      {
        alert("Please enter a valid number in the \"Contact Number\" field.");
        document.forms[0].pContact.focus();
        return (false);
      }

    else    if(!IsEmptyField('pEmail','Email')){
              return false;
       }
       
    else   if(!document.forms[0].pEmail.value.match(/^\w+([\.\-]\w+)*\@\w+([\-\.]\w+)*\.[a-z]{2,4}$/i))
      {
        alert("Wrong E-mail Address: "+document.forms[0].pEmail.value);
        document.forms[0].pEmail.select();
        document.forms[0].pEmail.focus();
        return false;
      }  
       

    else if   (document.forms[0].pAccessLevel.value == '')
    {
             alert("Access Level is a required field.");
              document.forms[0].pAccessLevel.focus();
              pass = false;

    }
    else if  ( (document.forms[0].pAccessLevel.value != 0 ) && (document.forms[0].pAccessLevel.value != 1 ) )
         {
              alert("Please Enter Your Access.");
              document.forms[0].pAccessLevel.focus();
              pass = false;

         }

         if (pass)
         {
              document.forms[0].action = "../admin/functions/fnc-listuser_datename.asp"
                document.forms[0].submit();
         }

    }

    //-->
    </SCRIPT>
    0
     
    LVL 3

    Expert Comment

    by:gnudiff
    Well, it depends, if you really want separate error messages for each occurance? I make them all together and present in one nice alert. Have you tried mine? It should work just copy/pasted into a file.

    I mean - if the field is blank, then it also definitely won't have 5 chars in it, and my script will note it, too.

    Also, you seem to spend a lot of time and work dealing with .charAt()s, when a simple regexp does the job.

    My script works for all the cases you wanted, except pAccessLevel (as you said it works fine already).

    It is your choice whether you use your approach or mine, however, wouldn't you agree that I solved your question?
    0
     
    LVL 2

    Expert Comment

    by:gbajramo
    Very elegant gnudiff. Nice use of array. Saved it in my favorites.
    0
     
    LVL 3

    Accepted Solution

    by:
    Thanks, gbajramo. :)

    Actually, if there were more fields, it'd make sense also to divide them by type and put regexp/type mapping in an array, too.
    (eg . -- warning: this is not valid javascript, just  pseudocode to show what needs done:

    fieldlist[" pUserName "].type="rxMin5Chars";
    fieldlist[[" pUserName "].type="rxMin5Chars";
    ...

    mapping

    ftypelist: ["regexp", "error message"]

    " rxMin5Chars": (/^[A-z0-0]{5,}$/ , "Minimum of 5 chars");
    "rx7digits": (/^\d{7}$/, "Field must be 7 digits");
    ...

    and then all those regexp checks could be made as one foreach:

    foreach field in (fieldlist)
       elem=forms[0].elements[field];
       if ( elem.search(ftypelist[elem.type]['regexp']) == -1)
              errors.push( ftypelist[elem.type]['error message']);

    ....

    But for 5-10 fields... can do manually too. :)
    0
     
    LVL 5

    Author Comment

    by:zamorin
    gnudiff,

    Your code works nicely, but my boss wants it to be a single alert per field (to follow other pages).

    With my code above, I now only have a problem with UseID alert and NRIC Number alert prompting one after the other. The rest is working o.k.

    0
     
    LVL 5

    Author Comment

    by:zamorin
    I got it working already, the problem was with the line : pass = false, it should have been return = false.

    Anyway, thanks for all the help.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
    Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    856 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

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now