Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Custom Javascript Validation

Posted on 2004-04-01
6
Medium Priority
?
581 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
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…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

636 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