?
Solved

Custom Javascript Validation

Posted on 2004-04-01
6
Medium Priority
?
580 Views
Last Modified: 2006-11-17
Hello,

I was wondering if there was a way to do the following:

1. Have a form that takes input (ie: User Name and Password)
2. Have a button that submits this information.
3. If the person has left the User Name or Password field blank then CUSTOM (my hand written code) javascipt will detect this and the page will stop processing and an alert will be displayed.
4. Only when the person has entered something in the User Name and Password fields will the form go to the code behind (server).

What is important to note is that I am not looking for a "Custom Validator" tag solution. I want javascript that I write to validate if the fields are blank and if they are, then an alert is displayed and the form does not go to the server for processing.

I have tried to put an OnSubmit="CheckForm(this)" on the form tag, and return false but it still goes to the server after that, even if the javascript function returns false. Maybe I am doing this wrong?

Thanks.
0
Comment
Question by:prodier
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 6

Accepted Solution

by:
KarunSK earned 2000 total points
ID: 10734805
OnSubmit should read:

OnSubmit="return CheckForm(this);"

If you leave out "return", the value returned by CheckForm is not considered, but goes ahead with the submit; the return tells it cancel the submission if the value is false.

I guess you have figured out the CheckForm() function, but here is a gist anyway:

function CheckForm()
{
 if (document.frmLogin.txtUserName.value == '')
 {
       alert('Enter Username!');
       return false;
 }
 return true;
}

HTH,
Karun.
0
 
LVL 7

Expert Comment

by:dante469
ID: 10735025
The attached will work....

Please notice the real aspSubmit is hidden via Javascript but is clicked from code after javascript validation.  You want to write .Net code against the aspSubmit.click event in codebehind...

BTW... Not against bonus points

Have Fun,
Dante

<body>
            <form id="Form1" method="post" runat="server">
                  <P>
                        <asp:TextBox id="uid" runat="server"></asp:TextBox><BR>
                        <BR>
                        <asp:TextBox id="pwd" runat="server"></asp:TextBox></P>
                  <P><INPUT type="button" value="Button" onclick="validate()"></P>
                  <P>
                        <asp:Button id="aspSubmit" runat="server" Text="aspSubmit"></asp:Button></P>
            </form>
            <script language="Javascript">
                  document.Form1.aspSubmit.style.display='none';
                  function chkuidpwd() {
                         var UID = document.Form1.uid.value;
                   var PWD  = document.Form1.pwd.value;

                     if (document.Form1.uid.value == "") {
                            self.alert("UserID can't be empty");
                              document.Form1.uid.focus();
                                return false;
                   }

             if (document.Form1.pwd.value == "") {
                  self.alert("Password can't be empty");
                  document.Form1.pwd.focus();
                  return false;
             }

             return true;
          }

      function validate() {
            if (chkuidpwd()) {
                  document.Form1.aspSubmit.click();
            }
                  
      }
            </script>
      </body>
0
 
LVL 7

Expert Comment

by:dante469
ID: 10735186
This approach is a little more straightforward, however will prevent all postback (even ones you may want related to other form elements)....

<body>
      <form id="Form1" method="post" runat="server" onsubmit="return(chkuidpwd());">
            <P>
            <asp:TextBox id="uid" runat="server"></asp:TextBox><BR>
            <BR>
            <asp:TextBox id="pwd" runat="server"></asp:TextBox></P>
            <P>
            <asp:Button id="aspSubmit" runat="server" Text="aspSubmit" ></asp:Button></P>
      </form>

<script language="Javascript">
      function chkuidpwd() {
                     var UID = document.Form1.uid.value;
           var PWD  = document.Form1.pwd.value;
                     if (document.Form1.uid.value == "") {
                self.alert("UserID can't be empty");
                document.Form1.uid.focus();
                return false;
            }
                     if (document.Form1.pwd.value == "") {
                          self.alert("Password can't be empty");
                          document.Form1.pwd.focus();
                          return false;
                    }

             return true;
          }
</script>

</body>
0
Quiz: What Do These Organizations Have In Common?

Hint: Their teams ended up taking quizzes, too.

 

Author Comment

by:prodier
ID: 10735356
Thank you everyone. KarunSK provided the key answer for me first which was the return keyword. I was missing that and it was the solution to my problem.

Thank you again everyone for your answers.
0
 
LVL 35

Expert Comment

by:YZlat
ID: 10735370
<HTML>
<HEAD>
<script language="javascript">
            <!--
function checkLogin() {
                  if (Form1.txtUserName.value == "" || Form1.txtPassword.value == "")
                        return false;
            }
            //-->
            </script>
      </HEAD>
      <body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">
                  <div align="center">
                        <table style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; FONT: 10pt verdana; BORDER-LEFT: 1px solid; BORDER-BOTTOM: 1px solid" cellSpacing="10" bgColor="peachpuff">
                              <tr>
                                    <td><asp:label id="lblUserName" runat="server" Text="User Name:" >
                        User Name:
                        </asp:label></td>
                                    <td><asp:textbox id="txtUserName" runat="server"></asp:textbox></td>
                              </tr>
                              <tr>
                                    <td><asp:label id="lblPassword" runat="server" Text="Password:" >
                        Password:
                        </asp:label></td>
                                    <td><asp:textbox id="txtPassword" runat="server" TextMode="Password"></asp:textbox></td>
                              </tr>
                        </table>
                        <br>
                        <asp:button id="btnSubmit" runat="server"  text="Login"></asp:button>
                        <br>
                        <p></p>
                        <asp:label id="lblWarning" runat="server" ForeColor="Red"></asp:label></div>
            </form>
</body>
</html>

Then in code behind in your Page_load procedure do the following:

 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
        'add client-side validation
        btnSubmit.Attributes.Add("onclick", "javascript:checkLogin();")
        If IsPostBack Then
         
            If ValidateUser(txtUserName.Text,  txtPassword.Text) Then
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
            Else
                lblWarning.Text = "Invalid Login!"
            End If
        End If
    End Sub

You'll also need a function ValidateUser(ByVal user as string, ByVal Password as string) As Boolean
that take two arguments user and password and validates them against the database and returns true on success and false otherwise
0
 
LVL 35

Expert Comment

by:YZlat
ID: 10735378
guess I'm too late
0

Featured Post

How To Reduce Deployment Times With Pre-Baked AMIs

Even if we can't include all the files in the base image, we can sometimes include some of the larger files that we would otherwise have to download, and we can also sometimes remove the most time-consuming steps. This can help a lot with reducing deployment times.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Suggested Courses

777 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