Tips on validating ASP.NET gridview textbox with javascript during the update process:

I've implemented a gridview on my aspx page:

<asp:GridView ID="gvPhoneBook" runat="server" AutoGenerateColumns="false" 
            ShowFooter="true" DataKeyNames="PhoneBookID"
            ShowHeaderWhenEmpty="true"

            OnRowCommand="gvPhoneBook_RowCommand" 
            OnRowEditing="gvPhoneBook_RowEditing" OnRowCancelingEdit="gvPhoneBook_RowCancelingEdit"
            OnRowUpdating="gvPhoneBook_RowUpdating" OnRowDeleting="gvPhoneBook_RowDeleting">

            <Columns>
                <asp:TemplateField HeaderText="First Name">
                    <ItemTemplate>
                        <asp:Label Text='<%# Eval("FirstName") %>' runat="server" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtFirstName" Text='<%# Eval("FirstName") %>' runat="server" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtFirstNameFooter" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:Label Text='<%# Eval("LastName") %>' runat="server" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLastName" Text='<%# Eval("LastName") %>' runat="server" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtLastNameFooter" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Contact">
                    <ItemTemplate>
                        <asp:Label Text='<%# Eval("Contact") %>' runat="server" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtContact" Text='<%# Eval("Contact") %>' runat="server" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtContactFooter" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email">
                    <ItemTemplate>
                        <asp:Label Text='<%# Eval("Email") %>' runat="server" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmail" Text='<%# Eval("Email") %>' runat="server" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtEmailFooter" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ImageUrl="~/Images/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px"/>
                        <asp:ImageButton ImageUrl="~/Images/delete.png" runat="server" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px"/>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:ImageButton ImageUrl="~/Images/save.png" runat="server" OnClientClick="return Validate(this);" CommandName="Update" ToolTip="Update" Width="20px" Height="20px"/>
                        <asp:ImageButton ImageUrl="~/Images/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px"/>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:ImageButton ImageUrl="~/Images/addnew.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px"/>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Seeking to validate the Email field when updating (no empty fields allowed).

This is what I attempted:-

function validate() 
{ 
 if(document.getElementById("<%=txtEmail.ClientID%>").value‌​=="")
 { 
 alert("Email Field can not be blank"); 
 document.getElementById("<%=txtEmail.ClientID%>").focus(‌​); 
 return false; 
 } 
 return true; 
 }

However, encountering an error stating txtEmail does not exist in the current context.

Also tried this method:-

<script type="text/javascript">
    function Validate(lnkUpdate) {
     var txtEmail;
     var row = lnkUpdate.parentNode.parentNode;
     txtEmail = row.getElementsByID("txtEmail");

     if (txtEmail.value == null) {
         alert("Email Field can not be blank"); 
     }
     }

The above method is being called upon clicking the update button but it's not functioning correctly. How can I achieve this using JavaScript? Where am I making mistakes?

Answer №1

To enhance your button, you can assign a class to it.

<EditItemTemplate>
                        <asp:ImageButton ImageUrl="~/Images/save.png" runat="server" class="button_save" CommandName="Update" ToolTip="Update" Width="20px" Height="20px"/>
                        <asp:ImageButton ImageUrl="~/Images/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px"/>
                    </EditItemTemplate>

Subsequently, you can monitor the click event of the specified class using javascript.

var buttonSave = document.getElementsByClassName("button_save");

for (var i = 0; i < buttonSave.length; i++) {
    buttonSave[i].addEventListener('click', Validate(buttonSave[i]), false);
}

Answer №2

Consider exploring aspnet Validation Controls for your project.

<asp:TextBox ID="txtEmail" Text='<%# Eval("itemid") %>' runat="server" />
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Email Field can not be blank" ControlToValidate="txtEmail"
  ValidationGroup="inGridView"></asp:RequiredFieldValidator>

Make sure to assign the ValidationGroup to the save button as well.

<asp:ImageButton runat="server" ValidationGroup="inGridView" />

There are various types of Validation Controls that can be controlled from code behind. For more information, refer to the documentation: https://msdn.microsoft.com/nl-nl/library/bwd43d0x.aspx

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

Switching button class when hovering over another div

When you click on the "collapsible-header" div, I want the text "TE LAAT" in the button to change to "NU BETALEN". Currently, the CSS code changes the text on hover, but I want it to change on click when the collapsible-header also has the active class. T ...

NodeJS Error: Attempting to access 'json' property from an undefined source

I'm in the process of setting up a CronJob to make an API call and save the response into the database: const CronJob = require("cron").CronJob; const btc_price_ticker = require("../../controllers/BtcExchange/Ticker"); const currency = require("../.. ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file. My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this? app.js (function() { var app = angula ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

In JavaScript, you can ensure that only either :after or :before is executed, but not both

My html slider is causing me some trouble <div class="range-handle" style="left: 188.276px;">100,000</div> Upon loading the page, I noticed that in Firebug it appears like this https://i.sstatic.net/Rgqvo.png On the actual page, it looks li ...

Discovering the most efficient route on a looped set of items

My question may not be fully comprehensible, but essentially it involves the following scenario: I have created an interactive presentation that displays static images in a sequence to generate an animation. By clicking the Play button, the animation prog ...

Automatically adjust Kendo Grid column widths, with the option to exclude a specific column from

Seeking a solution to dynamically adjust column widths in a Kendo Grid using column(index = n) or column(headingText = 'Address'). For automatically fitting column widths, the following approach can be used: <div id="example ...

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

What is the process for attaching the stack when initializing and throwing errors separately in JavaScript?

In all the documentation I've read, it consistently advises to both throw and initialize errors on the same line. For example: throw new Error("My error"); But what if you were to first initialize the error and then throw it on separate lines? For ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Converting CSV data into JSON format using NodeJs and integrating it with MongoDB

Here is how my CSV file is structured: "Some Comment here" <Blank Cell> Header1 Header2 Header3 Value1 Value2 Header4 Value3 Value4 I am looking to convert this into JSON format and store it in MongoDB as follows: Obj: { Key1: Header ...

RS256 requires that the secretOrPrivateKey is an asymmetric key

Utilizing the jsonwebtoken library to create a bearer token. Following the guidelines from the official documentation, my implementation code appears as below: var privateKey = fs.readFileSync('src\\private.key'); //returns Buffer let ...

When executed on the node REPL, lodash.sortBy will update the lodash value

When I access the node REPL, the following happens: > _ = require('lodash'); > // it displays the whole lodash object > _.sortBy(['1234', '123'], function (element) { return element.length; }); > [ '123&apos ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...