Solved

Custom Javascript Validation

Posted on 2004-04-01
6
569 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:prodier
Comment Utility
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
Comment Utility
<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
Comment Utility
guess I'm too late
0

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.

Join & Write a Comment

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

772 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

10 Experts available now in Live!

Get 1:1 Help Now