Solved

Custom Javascript Validation

Posted on 2004-04-01
6
575 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
6 Comments
 
LVL 6

Accepted Solution

by:
KarunSK earned 500 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
DevOps Toolchain Recommendations

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

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Need help on C# Linq query on object 6 53
How can I use SQL Stored Procedure to return FedEx Zone 17 41
Host asp.net pages 5 25
VB.Net How to Exit Sub - Exit Form??? 5 51
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

895 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

12 Experts available now in Live!

Get 1:1 Help Now