Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control.

I am looking to validate the text entered by users as alphanumeric characters and spaces only.

Allowed characters are: a-z, A-Z, 0-9, and space.

I want to perform this validation using JavaScript.

Platform: ASP.Net 2.0, C#

Here is what I have attempted so far...

<script type="text/javascript">

function IsValidCharNum(event) {
    var KeyBoardCode = (event.which) ? event.which : event.keyCode;
    if ((KeyBoardCode < 96 || KeyBoardCode > 123) && (KeyBoardCode < 65 || KeyBoardCode > 90) && (KeyBoardCode < 48 || KeyBoardCode > 57) && (KeyBoardCode !== 32)) {
        return false;
    }
    return true;
} </script>

When used with onkeypress="return IsValidCharNum(event)" for a textbox outside of the gridview and update panel, it works as expected.

Answer №1

If you want to ensure that a user only enters alphanumeric characters, you can use the RegularExpression Validator in the following way:

<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>

<asp:RegularExpressionValidator ID="REValphaOnly" runat="server" ErrorMessage="Please enter only alphanumeric." ControlToValidate="txtName" ValidationExpression="^[a-zA-Z0-9 ]+$"></asp:RegularExpressionValidator>

For more information, you can visit these links:

http://msdn.microsoft.com/en-us/library/ms972966.aspx

http://www.codeproject.com/Tips/472728/RegularExpressionValidator-In-ASP-NET

Answer №2

To implement this functionality, you can utilize JavaScript to trigger an event when a user types in a textbox.

<script type="text/javascript>
        function ValidateText(i) {
            if (/[^0-9a-bA-B\s]/gi.test(fieldname.value)) {
                alert("Please enter only alphanumeric characters and spaces in this field");
                fieldname.value = "";
                fieldname.focus();
                return false;
            }
        }
</script>

<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server" onkeyup ="ValidateText(this);"></asp:TextBox>
    </ItemTemplate>
</asp:TemplateField>

Answer №3

After much effort, I have successfully developed a function to validate user input

page.aspx

<script type="text/javascript>
  function CheckInput(event) {

      var KeyCode = (event.which) ? event.which : event.keyCode;

      if ((KeyCode < 96 || KeyCode > 123) && (KeyCode < 65 || KeyCode > 90) && (KeyCode < 48 || KeyCode > 57) && (KeyCode < 32 || KeyCode > 32)) {
         
          return false;

      }

      return true;

  }

<asp:TextBox ID="TextBox1" runat="server" onkeypress="return CheckInput(event)"></asp:TextBox>

Implementing this function with gridview and updatepanel functionality

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

In VueJS, the v-for directive allows you to access both parameters and the event object within

Imagine having nested elements that repeat using v-for in the following structure: <div id="container"> <div v-for="i in 3"> <div v-for="j in 3" v-on:click="clicked(i,j)"> {{i+&a ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...

JavaScript scripts are unable to function within an Angular directive's template due to compatibility issues

I'm facing an issue with a directive (function (angular) { 'use strict'; function digest(factory) { var directive = { restrict: 'E', templateUrl: '/js/app/digest/templates/digest.tem ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

Ensure the page is always updated by automatically refreshing it with JavaScript each time it

I'm currently working on a web application that makes use of JQuery. Within my javascript code, there's a function triggered by an onclick event in the HTML which executes this line: $('#secondPage').load('pages/calendar.html&apos ...

What is the best way to apply a background image to a DIV element using CSS

The main aim is to change the background image of a DIV using AJAX. $.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', function(data) { $.each(data.results, fun ...

The C# API call encounters issues when using HttpWebRequest, yet functions properly with Postman

I have encountered an issue with my Postman request. Here are the images I am working with: The expected result should be a URL like this: Now, I am attempting to replicate this process in a .Net Core 2.0 application using the code below: static void Ma ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

What is the best way to extract the content within a nested <p> element from an external HTML document using the HTML Agility Pack?

I'm currently working on retrieving text from an external website that is nested within a paragraph tag. The enclosing div element has been assigned a class value. Take a look at the HTML snippet: <div class="discription"><p>this is the ...

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

Next.js is causing me some trouble by adding an unnecessary top margin in my index.js file

I started a new project using next.js by running the command: yarn create next-app However, I noticed that all heading and paragraph tags in my code have default top margins in next.js. index.js import React, { Component } from "react"; import ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

What steps should I take to incorporate the delete feature as described above?

Click here to access the delete functionality Hello there, I need help implementing a delete function similar to the one provided in the link above. Below is the code snippet for your reference. I am utilizing the map method to extract data from an array ...

What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it. <a v-on:click="action($event)"> <span>entry 1</span> <span>entry 2</span> ...

Continuously receiving the value of undefined

I am currently working on a JavaScript Backbone project and I have declared a global object as follows: window.App = { Vent: _.extend({}, Backbone.Events) } In the initialize function, I have done the following: initialize: function () { window.App ...

Unable to pass a variable through ajax to another PHP file

I am currently facing an issue with passing a variable from one PHP file to another using ajax. In my 'index.php' file, there is a button that, when clicked, should pass the button's id to another PHP file named 'show_schedule.php' ...

"Threads snap as soon as they begin to be put to use

Encountering an issue with the command yarn run serve, the error log states: $ vue-cli-service serve INFO Starting development server... 10% building 2/2 modules 0 activeevents.js:173 throw er; // Unhandled 'err ...