Prevent the use of punctuation marks like full stops and commas in GridView Textbox

Within my GridView, there is a column that contains a textbox:

 <asp:GridView  style="width:75%;float:left"  
    ID="gvPieceOutturns" 
    ShowHeaderWhenEmpty="false"
    CssClass="tblResults" 
    runat="server" 
    OnRowDataBound="gvPieceOutturns_ItemDataBound"                          
    DataKeyField="ID" 
    AutoGenerateColumns="false"
    allowpaging="false"" />

    <Columns>
        <asp:TemplateField HeaderText="Comment" SortExpression="MemComment">
          <ItemTemplate>
            <asp:TextBox ID="txtMemComment" runat="server"></asp:TextBox>
          </ItemTemplate>
      </asp:TemplateField>
    </Columns>
</asp:GridView>

My goal is to validate the textbox so that it only allows letters and numbers, and not characters like full stops or commas.

When the user tabs off the textbox, a function is triggered:

protected void UpdateMemOutturnComment(object sender, EventArgs e)
{
    string Comment = hfMemOutturnComment.Value;
}

I am wondering how I can notify the user if they input an invalid character. Should I alert them right away or wait until they finish filling in the textbox?

Answer №1

If you're looking to validate user input using regular expressions, I suggest checking out this resource on using ASP.NET RegularExpressionValidators. These validators are designed to ensure that input meets specific criteria based on a regular expression pattern. When the input doesn't comply, the user is alerted and submission is prevented. The validation typically occurs when the user moves away from the input field.

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
    ControlToValidate="TextBox1" runat="server"
    ErrorMessage="Please enter only letters and numbers" 
    ValidationExpression="^[a-zA-Z0-9]*$" />

If you're not familiar with regex, it essentially matches strings containing both lowercase and uppercase letters, as well as numbers.

Answer №2

To perform validation on a TextBox, you can utilize a RegularExpressionValidator for general validation purposes. Additionally, you can trigger the onkeypress event of the TextBox for instant validation with an alert message:

<asp:TemplateField HeaderText="Comment" SortExpression="MemComment" ItemStyle-CssClass="memComment">
    <ItemTemplate>
        <asp:TextBox ID="txtMemComment" runat="server" onkeypress="ValidateMemComment(event);" />
        <asp:RegularExpressionValidator ID="revMemComment" runat="server" CssClass="validatorMemComment" ControlToValidate="txtMemComment" ValidationExpression="^[a-zA-Z0-9]*$" Text="*" ErrorMessage="Invalid character" ForeColor="Red" Display="Dynamic" />
    </ItemTemplate>
</asp:TemplateField>

The provided CSS class, .memComment, ensures that there are no line breaks between the TextBox and the validator in the cell:

.memComment
{
    white-space: nowrap;
}

The client-side onkeypress event handler would have the following structure:

<script type="text/javascript">
    function ValidateMemComment(event) {
        var code = event.which || event.keyCode;
        var isNumeric = (48 <= code && code <= 57);
        var isUpperAlpha = (65 <= code && code <= 90);
        var isLowerAlpha = (97 <= code && code <= 122);
        if (!isNumeric && !isUpperAlpha && !isLowerAlpha) {
            setTimeout(function () { alert("Invalid character!"); }, 0);
        }
    }
</script>

The setTimeout function is used here to ensure that the character is displayed before the alert message is shown.

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

I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to loa ...

Exploring the integration of Firebase with Next.js using getServerSideProps

I'm trying to retrieve the 'sample' document from Firestore using getServerSideProps only if a user is signed in. However, the current code I have isn't working and just returns 'can't read'. Is there a better solution or ...

Rotating the icon in Bootstrap Accordion upon opening

I am trying to customize a Bootstrap 4 accordion by conditional rotating the icon to point up when it is open and back down when closed. I managed to achieve this using CSS, but now I need to implement it conditionally based on active states rather than ev ...

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Is there a way to prevent Javascript from modifying styles when printing?

Is there a way to prevent JavaScript from affecting styling during printing? For example, if I'm using JavaScript to hide certain content but want that content to be visible when printed. I have hidden a div using JavaScript and now I'm trying ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

Using JavaScript to show a prompt message inside an h1 tag within a newly created div

I have developed a basic JavaScript program that opens a prompt dialog when the div tag is clicked, allowing the user to enter text. The program then creates a new div element and displays the entered text above it. However, I am facing an issue where I wa ...

Struggling to incorporate logout feature with node and passport js

Currently delving into the world of node js, I am in the process of creating a boilerplate utilizing passport js, react, and redux. The issue at hand involves trouble implementing log out functionality as my attempts to log out have been unsuccessful. Anyo ...

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

Easy Steps for Mapping Json Data into an Array

Here is the JSON Format I am working with: { "Data": { "-template": "Parallax", "Explore": { "IslandLife": { "TourismLocation": [ { "Title": "Langkawi", "Latitude": "6.350000", "Longitude": "99.800000", "YouTub ...

Showcase a sizable picture broken down into smaller sections

I am interested in creating a mapping application similar to Google Maps that can asynchronously load images from the backend. I am seeking guidance on where to begin and how to proceed in this endeavor. The ultimate goal is to have the image displayed w ...

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

Alerting JavaScript with element Selector doesn't function at full capacity

I am currently implementing Notify JS from the following source : Below is the HTML code I am using: <div> <p><span class="elem-demo">aaaa</span></p> <script> $(".elem-demo").notify( "Hello Box" ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...

What can be done to ensure smooth functionality of my nested navigation menu on mobile devices?

I'm utilizing the incredible features of Base Web for my website. One of the components I am using is a menu with a child menu, based on this example. The menu works perfectly fine on desktop - when I hover over an option, the child menu appears. Howe ...

Swap the image source with a different image attribute when making the website responsive

I have implemented a custom attribute for the img tag in my code, such as data-tablet and data-mobil <div class="myDiv"> <img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg"> </div> My goal is to have the image source c ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...