Custom validation on the client side using ASP.NET and JavaScript WebMethods

I am encountering an issue with client-side validation using a JavaScript function. On my ASP.NET C# page, I have a WebMethod that successfully validates data entered by the user. The page includes a textbox with an AJAX AutoCompleteExtender, which is working correctly. I am trying to use a CustomValidator that calls a JavaScript function to validate the data. The WebMethod, which retrieves data from a SQL database, is executing properly. However, I am facing a problem with setting the args.IsValid property within the OnSuccess function. The issue is that the args.Value and the result from the OnSuccess function are not accessible to each other, making it challenging to evaluate and set the validity of the data. I have tried using hidden fields and global variables in JavaScript, but they are not being set before the evaluation to set the args.IsValid. The only way I have managed to get the validation error message to display is by manually setting the args.IsValid and issuing an alert message at the end of the JavaScript function. I am looking for a solution that will display a message next to the textbox without the need for an alert. Ultimately, this validation will be implemented in a gridview with input boxes for multiple row edits. Utilizing a dropdown list with server-side validation is not suitable for my requirements.

Here is the JavaScript function I am using:

function pmValidateGLAccount(oSrc, args) {
    var GLIsValid;
    PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess);
    function OnSuccess(result) {
        if (args.Value != result) {
            GLIsValid = false;
        } else {
            GLIsValid = true;
        }
    };
} 

Here is the CustomValidator code:

<asp:CustomValidator ID="CustomValidator1" 
runat="server" 
ControlToValidate="TextBox1"  
ValidationGroup="vg_test" 
ClientValidationFunction="pmValidateGLAccount" 
ErrorMessage="Error: Please Enter an Account Number from the list" 
Display="Dynamic"></asp:CustomValidator>

And here is the WebMethod code:

[System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()]
public static string ValidateGLAccountAccess(string GLAccountNum)
{
    // Code for the WebMethod
}

Answer №1

For those still struggling with synchronous client-side validation, I finally cracked the code. I hesitated to delve into jQuery at first, but now I wish I had done it sooner.

My goal was to create a textbox autocomplete feature that would send the username to the database and retrieve user-specific data. To ensure only valid inputs from the autocomplete list are accepted in the textbox, I used CustomValidator with jQuery. This approach involved sending the final input string and username to the database. If a matching record was found, the selection was considered valid; otherwise, it was marked as invalid.

I faced challenges along the way, so I wanted to provide a comprehensive guide for others. Even if you're new to jQuery like I was, implementing this solution with it turned out to be surprisingly quick. Hopefully, this guide will assist someone in need out there.

Here's a step-by-step breakdown of what I did:

  1. Downloaded the jQuery script and placed it in my scripts folder. Added a reference to jQuery in the header section of my MasterPage.Master file. Updated the ScriptManager in the body to EnablePageMethods.

    <script type="text/javascript" src="/scripts/jquery-1.4.2.js"></script> 
    
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    
  2. Inserted the JavaScript code inside the content placeholder in TextBoxAutoFill.aspx.

    <script type="text/javascript">
        function pmValidateGLAccount(oSrc, args) {
            $.ajax({
                type: "POST",
                async: false,
                url: "TextBoxAutoFill.aspx/ValidateGLAccountAccess",
                data: "{ GLAccountNum: " + "'" + args.Value + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { args.IsValid = response.d; }
            });
        }; 
    </script>
    
  3. Created the TextBox, AutoCompleteExtender, and CustomValidator components.

    <asp:TextBox TabIndex="1" autocomplete="off" ID="TextBox1" runat="server" Width="250px" ValidationGroup="vg_test"></asp:TextBox>
     <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" 
         runat="server" 
         EnableCaching="true"
         CompletionSetCount="10"
         ShowOnlycurrentWordInCompletionListItem="true"
         CompletionInterval="500" 
         CompletionListCssClass="AJAXAutosuggestTextBox" 
         DelimiterCharacters="" 
         Enabled="True" 
         ServiceMethod="GetAccountNumbers" 
         TargetControlID="TextBox1" 
         MinimumPrefixLength="4"
         >
    </asp:AutoCompleteExtender>
    <asp:CustomValidator ID="CustomValidator1" 
        runat="server" 
        ControlToValidate="TextBox1"  
        ValidationGroup="vg_test" 
        ClientValidationFunction="pmValidateGLAccount" 
        ErrorMessage="Error: Please enter an account number from the list" 
        Display="Dynamic"></asp:CustomValidator>
    
  4. Implemented the WebMethod for AutoCompleteExtender (located in the TestBoxAutoFill.aspx.cs file).

    [System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()]
    public static List<string> GetAccountNumbers(string prefixText, int count)
    {
        // Code for retrieving account numbers based on user
    }
    
  5. Implemented the WebMethod for validation (also in the TestBoxAutoFill.aspx.cs file).

    [System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()]
    public static bool ValidateGLAccountAccess(string GLAccountNum)
    {
        // Code for validating the GL account access
    }
    

Answer №2

I have limited experience with .NET C# but I typically rely on JQuery validation and AJAX for web applications.

While I'm not able to test it out, here are some suggestions that might help:

  1. Double-check that PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess) is returning the correct result.

  2. Attempt the following code and debug it by using alert(args.IsValid) afterwards:

    function pmValidateGLAccount(oSrc, args) {
    var GLIsValid;
    args.IsValid = false;
    PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess);
    function OnSuccess(result) {            
        if (args.Value != result) {
            GLIsValid = false; // you may omit this line
            args.IsValid = false;
            alert(args.IsValid);
        }
        else {
            GLIsValid = false; // you may omit this line
            args.IsValid = true;
            alert(args.IsValid);
        }
    } 
    

    }

  3. If this doesn't address your concern, consider declaring "var GLIsValid;" as a global variable outside the function. Defining it within the function limits its accessibility. Thank you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to display a div in Angular when hovering with ElementRef and Query List

I am having trouble implementing a ngFor loop in my project where I want to display a div on mouse hover using the @Input notation. This is how my HTML code looks: <div class="col s12 m6" style="position: relative" *ngFor="let res of hostInfo.resident ...

send additional form elements to the AJAX suggestion box script

** shifted to this location: Numerous similar AJAX suggestion boxes without IDs I enlisted the help of a developer to create a jQuery AJAX suggestion box script some time ago, and it has been working flawlessly. Now, I am striving to understand it better ...

Problem with sending variable via AJAX

Hey everyone, I'm attempting to send form data along with an extra variable using AJAX. Here's the code snippet: function tempFunction(obj) { var data = $('form').serializeArray(); data.push( { no: $(obj).at ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

Align Text Center inside a Magical H1 Heading Tag

I'm having a bit of trouble with something that should be simple. I want to center the text inside my h1 tag on a wizard, and I've added this CSS to my stylesheet.css: .h1textalign { text-align:center; } Here's how I'm trying to apply ...

I'm running into an InvalidSelectorError and I could use some assistance in properly defining

As I gaze upon a massive dom tree, my task using NodeJS/Selenium is to locate an element by the title attribute within an anchor tag and then click on the associated href. Despite being a newcomer to regex, I am encountering numerous errors already. Below ...

How to use hooks in NETXJS to pass data from a page to a component

Hey there, how are you doing? I am currently working on a project using Next.js and styled components. I am trying to change a string using props in my layout component, where the main content is dynamic per page. Page 'prueba.js' import React f ...

Leveraging jQuery for validating a value by comparing it to another input value

Currently, I am working on a validation task for input fields related to hour rates. The aim is to ensure that once a base hour input is added, the other input values cannot exceed the value entered in the first base rate column. Essentially, the initial i ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

What makes styling a success button in @material-ui so challenging?

I am currently utilizing the user interface framework found at https://material-ui.com/ My primary aim is to obtain a success Button and Chip. Can anyone provide insight on achieving this goal without resorting to less-than-ideal methods like those discus ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Implementing Vuetify tooltips in a datatable

Attempting to incorporate tooltips into a vuetify datatable, but encountering issues. Below is the required template for using a tooltip: <template v-slot:item.state="{ item }"> <div :class="lights(item)"></div> </template> Im ...

How to grasp this particular date within nodeJS?

Can anyone help me properly format this date 2018-11-04T14:00:00-07:00? I obtained it from the NWS API but I've had trouble using Date() and similar functions. ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...