473,320 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to invoke CustomValidator function and page validation function in JavaScript?

88 64KB
Basic workflow of my page

Image of Payment Page:
https://1drv.ms/u/s!Ava3iL9se3C3gTF_XJ_RiBBsWDHs

In ASP.Net, I have a payment page that has a name textbox (txtName), a PIN textbox (txtPin) and two textboxes (txtPaymentDate and txtPaymentTime) containing payment date and time respectively. The page also has a payment button (btnPay). txtName has a RequiredFieldValidator that checks if the field is blank. txtPin has a CustomValidator that checks if the field has a six-digit numeric value. A third CustomValidator makes sure that either both txtPaymentDate and txtPaymentTime are clear, or both of them are selected at the same time. Just one of them can't be selected. All these validation checks need to be on the client side.

While clicking btnPay, it'll check on the client side if txtPaymentDate and txtPaymentTime are selected together. If yes, then the value of txtPaymentDate should be between 01/01/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. If the value is not within the specified dates, an alert message will be displayed and click event cancelled.

If all the above validations are successful, btnPay postback will occur and the server side event of btnPay will be fired.

This is what I want to achieve in the exact order on clicking btnPay:
  1. All the validations of the validator controls on client side will take place. If validation of any validator control on client side fails, it'll stop btnPay click event. No need to go to step 2 either.
  2. On successful validation of all the validator controls above, a client side validation will check if txtPaymentDate and txtPaymentTime are both selected, and if value of txtPaymentDate is within the specified range. If this validation fails, btnPay click event is stopped too.
  3. Only if the above two steps are successful, btnPay postback will occur and the server side event of btnPay will be fired.

What's actually happening while clicking btnPay:
  1. None of the "client side" validations of the validator controls are occurring at all. Instead, the "server side" validations of the respective validator controls are occurring.
  2. Once step 1 is successfully validated, client side validation to check if value of txtPaymentDate is within specified range is occurring successfully. It's also blocking btnPay click event if this validation is not true, which is good as per requirement.
  3. If the above two validations are successful, btnPay postback is taking place successfully firing server side event of btnPay, which too is OK as per requirement.

Step 1 highlighted above is my problem. When I click btnPay, instead of executing the "CLIENT SIDE" functions of the validators, the respective "SERVER SIDE" functions of the validators are being executed. I want them to execute on the client side. However, surprisingly, if I delete OnClientClick="return Client_ValidatePage()" from btnPay, all client side functions of the validator controls are working fine. Seems like the client side functions of the validator controls are clashing with OnClientClick="return Client_ValidatePage()" of btnPay. How can I get rid of this?

aspx page:
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/User.master" AutoEventWireup="true" CodeFile="Payment.aspx.cs" Inherits="Payment" %>
  2.  
  3. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  4.     <script type="text/javascript">
  5.         // Test if txtPin is not blank, doesn't contain alphanumeric value and contains exactly six digits.
  6.         function Client_ValidatePin(source, arguments) {
  7.             arguments.IsValid = /^[0-9]{6}$/.test(arguments.Value);
  8.         }
  9.  
  10.         // Test if both txtPaymentDate and txtPaymentTime are selected or none of them at all.
  11.         function Client_ValidatePaymentDateTime(source, arguments) {
  12.             var paymentDate = document.getElementById("<%=txtPaymentDate.ClientID%>").value;
  13.             var paymentTime = document.getElementById("<%=txtPaymentTime.ClientID%>").value;
  14.  
  15.             arguments.IsValid = (paymentDate.length == 0 && paymentTime.length == 0) || (paymentDate.length > 0 && paymentTime.length > 0);
  16.         }
  17.  
  18.         function Client_ValidatePage() {
  19.             // Test if payment date is less than 01/01/1753 12:00:00 AM or greater than 12/31/9999 11:59:59 PM.
  20.             var paymentDate = document.getElementById("<%=txtPaymentDate.ClientID%>").value;
  21.             var paymentTime = document.getElementById("<%=txtPaymentTime.ClientID%>").value;
  22.  
  23.             if (paymentDate.length > 0 && paymentTime.length > 0) {
  24.                 if (paymentDate < "1753-01-01" || paymentDate > "9999-12-31") {
  25.                     alert('All dates should be between 01/01/1753 12:00:00 AM and 12/31/9999 11:59:59 PM');
  26.                     return false;
  27.                 }
  28.             }
  29.  
  30.             return true;
  31.         }
  32.     </script>
  33.     <div id="divAlert" role="alert" runat="server">
  34.     </div>
  35.     <div class="row">
  36.         <div class="col-md-9">
  37.             <h4>Payment</h4>
  38.             <hr />
  39.             <div class="form-group row">
  40.                 <asp:Label ID="Label1" runat="server" class="col-md-2 col-form-label" Text="Name:"></asp:Label>
  41.                 <div class="col-md-7">
  42.                     <asp:TextBox ID="txtName" class="form-control" runat="server" MaxLength="50"></asp:TextBox>
  43.                     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" class="text-danger" ErrorMessage="Name is required!" ControlToValidate="txtName"></asp:RequiredFieldValidator>
  44.                 </div>
  45.             </div>
  46.             <div class="form-group row">
  47.                 <asp:Label ID="Label2" runat="server" class="col-md-2 col-form-label" Text="PIN:"></asp:Label>
  48.                 <div class="col-md-7">
  49.                     <asp:TextBox ID="txtPin" class="form-control" runat="server" MaxLength="6"></asp:TextBox>
  50.                     <asp:CustomValidator ID="PinValidator" runat="server" ControlToValidate="txtPin" ValidateEmptyText="true" ClientValidationFunction="Client_ValidatePin" OnServerValidate="PinValidator_ServerValidate" class="text-danger" Display="Static" ErrorMessage="A 6-digit number is required!"></asp:CustomValidator>
  51.                 </div>
  52.             </div>
  53.             <div class="form-group row">
  54.                 <asp:Label ID="Label3" runat="server" class="col-md-2 col-form-label" Text="Date/Time:"></asp:Label>
  55.                 <div class="col-md-7">
  56.                     <div class="form-inline">
  57.                         <asp:TextBox ID="txtPaymentDate" class="form-control" runat="server" TextMode="Date"></asp:TextBox>
  58.                         <asp:TextBox ID="txtPaymentTime" class="form-control" runat="server" TextMode="Time"></asp:TextBox>
  59.                     </div>
  60.                     <asp:CustomValidator ID="PaymentDateTimeValidator" runat="server" ClientValidationFunction="Client_ValidatePaymentDateTime" OnServerValidate="PaymentDateTimeValidator_ServerValidate" class="text-danger" Display="Static" ErrorMessage="Both dates or none of them are required!"></asp:CustomValidator>
  61.                 </div>
  62.             </div>
  63.             <asp:Button ID="btnPay" runat="server" Text="Make Payment" OnClientClick="return Client_ValidatePage()" OnClick="btnPay_Click" />
  64.         </div>
  65.     </div>
  66. </asp:Content>
  67.  
  68.  
Code-behind:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. public partial class Payment : System.Web.UI.Page
  9. {
  10.     private bool Server_ValidatePage()
  11.     {
  12.         // If both payment date and payment time are selected, then check if payment date is not a valid date.
  13.         if (!String.IsNullOrEmpty(txtPaymentDate.Text) && !String.IsNullOrEmpty(txtPaymentTime.Text))
  14.         {
  15.             if (!Utilities.IsValidDateTime(txtPaymentDate.Text))
  16.             {
  17.                 divAlert.Attributes["class"] = "alert alert-danger";
  18.                 divAlert.InnerText = "All dates should be between 01/01/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.";
  19.                 return false;
  20.             }
  21.         }
  22.  
  23.         return true;
  24.     }
  25.  
  26.     protected void Page_Load(object sender, EventArgs e)
  27.     {
  28.         if (IsPostBack)
  29.         {
  30.             divAlert.InnerText = string.Empty;
  31.             divAlert.Attributes["class"] = "d-none";
  32.         }
  33.     }
  34.  
  35.     protected void PinValidator_ServerValidate(object source, ServerValidateEventArgs args)
  36.     {
  37.         try
  38.         {
  39.             // Test if txtPin is not blank, doesn't contain alphanumeric value and contains exactly six digits.
  40.             args.IsValid = System.Text.RegularExpressions.Regex.IsMatch(args.Value, "^[0-9]{6}$");
  41.         }
  42.  
  43.         catch (Exception ex)
  44.         {
  45.             args.IsValid = false;
  46.         }
  47.     }
  48.  
  49.     protected void PaymentDateTimeValidator_ServerValidate(object source, ServerValidateEventArgs args)
  50.     {
  51.         try
  52.         {
  53.             // Test if both txtPaymentDate and txtPaymentTime are selected or none of them at all.
  54.             args.IsValid = (txtPaymentDate.Text.Length == 0 && txtPaymentTime.Text.Length == 0) || (txtPaymentDate.Text.Length > 0 && txtPaymentTime.Text.Length > 0);
  55.         }
  56.         catch (Exception ex)
  57.         {
  58.             args.IsValid = false;
  59.         }
  60.     }
  61.  
  62.     protected void btnPay_Click(object sender, EventArgs e)
  63.     {
  64.         if (Page.IsValid && Server_ValidatePage())
  65.         {
  66.             // Write code for payment.
  67.  
  68.             // If payment is successful...
  69.             divAlert.Attributes["class"] = "alert alert-success";
  70.             divAlert.InnerText = "Payment completed successfully.";
  71.         }
  72.     }
  73. }
  74.  
Any help on this issue is highly appreciated.

Technology used: Visual Studio 2017, Bootstrap 4.5.0 on Windows 7.

Feel free to ask further if my post is not clear to you.
Regards
Jun 16 '20 #1
0 4617

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: J. Hall | last post by:
Hi guys, Witten a function to check two input boxes, ensure that only one has a numerical value in, but I'm gettng the javascript error 'Object expected'?? function...
39
by: Randell D. | last post by:
Folks, I'm sure this can be done legally, and not thru tricks of the trade - I hope someone can help. I'm writing a 'tool' (a function) which can be used generically in any of my projects. ...
4
by: SteveS | last post by:
Does anyone know if it is possible to invoke a Javascript function in a web page from an external application? I've got some data that I want to pass from a windows application to a web page...
3
by: RSB | last post by:
Hi Everyone, I have this TextBox with the TextMode="MultiLine". so now it does not validate the text in the TextBox for the MaxLength SO i have decided to execute a CustomValidator for this...
2
by: Jeff Tolman | last post by:
Is there anyway for a Javascript routine to determine if the validators on its page are successful? What's happening is I'm adding a javascript routine to the Submit button of a page (to perform...
3
by: karmenkrile | last post by:
In html i have some question, and the answers are radio buttons ... the names of variables in html are array ... like question, question ... etc. and every question has multiple value, depending...
6
by: Syren Baran | last post by:
Hi, is it possible to write two functions which both require a function as an argument and both being able to use the other function as an argument? Afaik the address of a function is not known...
10
by: Richard Heathfield | last post by:
Stephen Sprunk said: <snip> Almost. A function name *is* a pointer-to-function. You can do two things with it - copy it (assign its value to an object of function pointer type, with a...
12
by: sinbad | last post by:
hi, is it possible to get function name from function pointer. I am using gcc compiler on linux. thanks
13
by: Andrew Falanga | last post by:
HI, Just a warning, I'm a javascript neophyte. I'm writing a function to validate the contents of a form on a web page I'm developing. Since I'm a neophyte, this function is quite simple at...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.