Utilizing OnServerValidate and ClientValidationFunction for Custom Validation

I am encountering issues with the CustomValidation control as I am trying to validate if the year entered in the date of birth field is at least 20 years less than the graduation year selected from a drop-down list. I attempted to use the ClientValidationFunction as follows:

<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>

Here is the script provided:

<script type="text/javascript">

function GraduationYearValidation(sender, args) {

    var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());

    var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);

    if ((brithYear - gradeYear) < 20) {
        return args.IsValid = true;
    }
    else {
        return args.IsValid = false;
    }
}

I encountered errors stating "document.getElementById(...) is null" and "GraduationYearValidation is not defined."

Therefore, I attempted to perform server-side validation by:

<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>

The code behind includes:

protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
        int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);

        if ((gradeYear - brithYear) < 20)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }

Despite implementing

Page.Validate("SaveEducationStep");
and checking Page.IsValid before saving, the solution did not work for me. Any suggestions regarding both scenarios would be greatly appreciated. Thank you.

Answer №1

Validation on the client side is operational, please review your code


<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:DropDownList ID="dddate" runat="server">
        <asp:ListItem Text="2014" Value="2014"></asp:ListItem>
        <asp:ListItem Text="2013" Value="2013"></asp:ListItem>
        <asp:ListItem Text="2012" Value="2012"></asp:ListItem>
        <asp:ListItem Text="2011" Value="2011"></asp:ListItem>
    </asp:DropDownList>
    <asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true"             runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />

 <script type="text/javascript">
    function abc(sender, args) {


        var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());

            var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
            if ((gradeYear - birthYear) > 20) {
                return args.IsValid = true;
            }
            else {
                return args.IsValid = false;
            }
        }


</script>

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

Safari (on both mobile and Mac) has experienced a change in the hitbox for buttons

I'm experiencing an issue with a simple HTML button on my website. While it works perfectly on Google Chrome, users running Safari on macOS and iOS are facing a problem where the hitbox of the button is offset by about 50px above the actual button are ...

Ways to position the navigation menu alongside a search bar and a dropdown tab?

My navigation bar includes a search form, multiple links, and a dropdown link leading to additional links. Unfortunately, I'm struggling to align everything on the same line within the navbar. This is the current output: View My HTML Page Below is ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

React JS server conditional response malfunctioning

I've been facing issues with receiving a conditional response from an Express server for a React application. Check out the server-side code below: app.get('/api/checklogin', (req, res) => { var val = req.session.user ? false : tru ...

"Is it possible for a JSON array to have a length of zero even

After receiving a JSON response from the server and converting it into a Javascript object, the structure looks like this: var response = { key1:[], key2:[], key3:[], key4:[], key5:[] } Once the request is complete, the response objec ...

A React component utilizing dangerouslySetInnerHTML and including CSS styles

One of my React components displays the following element: <div dangerouslySetInnerHTML={{__html: this.props.htmlString}}/> While the html renders correctly, I am facing a challenge with my client-side CSS code affecting the component I am renderin ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Utilize Recurly's Node to generate a transaction with stored billing details

I need help creating a transaction using Recurly stored billing information. I am currently using the node-recurly module in my Node.js application. https://github.com/robrighter/node-recurly Below is the code snippet that I have written: recurly.transa ...

Unable to retrieve data from the $.getJSON method

Using $.getJSON in jQuery, I am retrieving the necessary data from the server. Below is an example of how it is structured: $.getJSON("/dataParser/parseVoltage",function(jsondata, status) { if (status == "error") { console.log("Error occurred whil ...

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Using $scope in hyperlinks - AngularJS

I have an array of items stored in the $scope.cart variable like this; $scope.cart = []; The items in the array include id, name, and other properties. I'm trying to include the items in a href attribute like so; <a href="http://www.example.co. ...

evaluating each element in a list against another

I'm attempting to check if an element exists in another list, but the lists are not in order and they are of different sizes. let list1 = [10 , 4 , 5] let list2 = [4 , 5] I attempted a solution, however it only works when the elements are in the same ...

Analyzing two separate lists from distinct tables using EntityFramework

I need to conduct a comparison between two datasets obtained from separate tables var firstList = db.exclure.Where(w => w.type.Contains("Object class")) .GroupBy(g => new {libelle = g.libelle,}) .Selec ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

Change the color of an HTML input box dynamically in JavaScript if the inserted value falls within a specified range

Hi there, I'm currently facing a challenge where I need to verify if the value entered by the user into an input box on my PHP page falls within a specific range. If the value is not within this range, I want to either change the text color in the inp ...

What is causing this code to not produce the expected result of 8.675?

Recently, I encountered a challenge on freecodecamp I managed to write the code successfully, but unfortunately, my browser crashed and I lost all the progress. When I attempted to rewrite the code, it was returning an incorrect answer (a value of 2). I& ...

Is there a way to upload numerous images from my local disk onto a canvas using Fabric.js?

I'm currently working on an innovative Image Collage application using the power of HTML5 canvas and Fabric.js. One of the key features I want to implement is the ability for users to simply drag and drop files into the designated 'File Drag and ...

Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? https://i.sstatic.net/CMi3D.png I've been looking into how to submit "multipart/form-data" from VueJs. What I nee ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...