JavaScript confirm function fails to validate a required field validator

Utilizing the required field validator to validate a text box and prompting for confirmation on the click of a submit button using the confirm() function in JavaScript has posed a challenge. Upon pressing OK in the confirmation box, the page refreshes and the required field validator fails to halt the process when the text box is left empty. After researching on Stack Overflow, I attempted to use a custom validator to prevent this issue, but unfortunately, I was unable to resolve it. Here is the code snippet:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" ValidationGroup="one" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
    <asp:TextBox ID="TextBox1" runat="server" ValidationGroup="one"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" 
        OnClientClick="validate();"  ValidationGroup="one" onclick="Button1_Click"/>
    <asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" runat="server" ValidationGroup="one" ErrorMessage="CustomValidator"></asp:CustomValidator>

    <script type='text/javascript'>   
           function validate() {
            var cv = document.getElementById('MainContent_CustomValidator1');
            if (cv) {
                cv.isValid = confirm('Are you sure you want to update the record?');
            }
     }  </script>

Answer №1

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" ValidationGroup="one" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
    <asp:TextBox ID="TextBox1" runat="server" ValidationGroup="one"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" 
        OnClientClick="return validate();"  ValidationGroup="one" onclick="Button1_Click"/>
    <asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" runat="server" ValidationGroup="one" ErrorMessage="CustomValidator" ClientValidationFunction="TextBox1Client"></asp:CustomValidator>

 <script type='text/javascript'>   
        function validate() {
          if(confirm('are you sure want to proceed?')){
          return true;
          }
          else
          {
          return false;
          }
       }
//a custom validation client function needs to be added as well  
       function TextBox1Client(sender, args) {
       //insert custom code here
        args.IsValid = false;
        //OR
        args.IsValid =true;
       }
    </script>

Answer №2

Experiment with this code snippet that utilizes Page_ClientValidate:

 <asp:Button ID="Button1" runat="server" Text="Button" 
        OnClientClick="Javascript:if(Page_ClientValidate('one')){return validate();}"  ValidationGroup="one" onclick="Button1_Click"/>

Answer №3

Revise your code in the following manner

if(confirm('are you sure you want to update the record ?') == false){
  return false;
}

Thank you.

Answer №4

JavaScript is case sensitive, remember to pay attention to capitalization:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" ValidationGroup="one" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="one"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" 
    OnClientClick="validate();"  ValidationGroup="one" onclick="Button1_Click"/>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" runat="server" ValidationGroup="one" ErrorMessage="CustomValidator"></asp:CustomValidator>

<script type='text/javascript'>   
       function validate() {
        var cv = document.getElementById('MainContent_CustomValidator1');
        if (cv) {
            cv.isValid = confirm('Are you sure want to update record?');
        }
 }  </script>

Don't forget to capitalize the 'i' in isValid.

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

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

What should we do to resolve the uncommon use of the 'this' es-lint error? Which rule should we disable?

Recently, I encountered an issue with my Nuxt setup that is configured with el-lint and prettier. Every time I try to use 'this' within my template, it throws up an error unexpectedly. 6:15 error Unexpected usage of 'this' vue/this ...

Retrieve the current height of the iFrame and then set that height to the parent div

Within a div, I have an iFrame that needs to have an absolute position for some reason. The issue is that when the iFrame's position is set to absolute, its content overlaps with the content below it. Is there a way to automatically adjust the height ...

What causes the automatic addition of a few hours to the date when retrieving UTC date from PostgreSQL using C#?

I have a situation where the UTC date is stored in postgress, but I need to display that date in the server's timezone. To achieve this, I made the following changes: The object selectedAttempt contains all the data stored in postgress. var assignmen ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

How to send data to Material-UI drawer components

In the component called Setup, there are input fields that each hold their own data stored in an object named dropdowns. Alongside each input field, there is a drawer component containing the ID of that specific input field. I have a function called handle ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Comparing jQuery and Yahoo UI API Design

I find myself puzzled by the contrasting design approaches of jQuery and Yahoo UI APIs. I must confess, I have a strong aversion to the jQuery API, but my knowledge in web programming and JavaScript is limited, so I could be completely mistaken and end up ...

Usercontrol: DragDrop event not triggering for internal object, whereas DragEnter executes successfully

My issue can be summed up by the title. Here is a detailed explanation of what I'm facing: I am developing an application with a TabControl that I populate with TabPages at runtime. Initially, each TabPage had a ListView created in code, with AddHand ...

Connecting to a fresh dynamic route does not impact the getInitialProps data

I am struggling to understand the difference between componentDidMount and getInitialProps. Despite my best efforts to research, I still can't figure out when to use each one in my specific case. Let me give you some context. I have a page called /co ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

How to Determine If a String Represents an HTML Tag Using jQuery

Checking if a string is an HTML tag can be tricky. I've tried various methods found on Google, but none have been successful so far: var v = $(string).html() ? 1 : 0; --or---------------------------------------------- var htmlExpr = new RegExp("/^( ...

Obtaining information from a database and integrating it into introjs utilizing JSON

Currently, I am using IntroJs and JSON to call the introjs. I am wondering if it is possible to store data/text/info in a database and then retrieve it using JSON? <h2 id="welcomeMsg">Welcome back,<asp:Label ID="lbl_WelcomeName" runat="server" Te ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Is there a way to keep a label in a Material-UI TextField from getting obscured by an adornment when the input is not in focus?

Here is the code for my custom TextField component: <TextField fullWidth: true, classes, helperText: errorText, FormHelperTextProps: getInputProps({ error }), InputProps: getInputProps({ error, endAdornment: error ? <Warning ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

Contrasting $interval and setInterval functions in AngularJs

I am trying to grasp the distinction between $interval and setInterval. I have come up with this test: Dashboard.prototype.updateTotalAppointments = function(){ //console.log(); this.appointmentsCount = this.appointmentsCount +1; console.log(this.appointm ...

Dynamic Menu Navigation (No Bootstrap Required)

My Navbar is working perfectly in the original mode but when the screen width is less than 950px, it displays the buttons stacked vertically. However, the dropdown button opens the dropdown content on the wrong side. I want the dropdown content to appear u ...

Generating replicated elements at varying positions

After discovering that my previous question, which can be found here, is currently not feasible due to limitations with html2canvas only taking 'snapshots', I have chosen to approach the problem differently. The new approach involves making an o ...

Are there any additional features available in NetSuite that allow for viewing multiple pages within a PDF document?

I'm looking to compile a list of all available pick tickets and then consolidate them into a single PDF file. Unfortunately, I am only able to generate one page per ID. var transactionFile = render.pickingTicket({ entityId: 501, printMode: render.Pri ...