Blocking certain charter inputs in ASP.NET can be achieved by implementing custom validation logic or

Here is an ASP.NET code snippet that prompts the user for input. The accompanying JavaScript ensures that the user does not leave the input field empty. Now, the goal is to prevent users from entering certain characters like (|,@,#,$) using the same JavaScript function. Any ideas on how this can be achieved?

<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onblur="CheckTxtBox(this);"></asp:TextBox>

function CheckTxtBox(sender) {
          if (sender.value == "") {
              alert("Please enter Address 1");
              return false;
          }
      }

Answer №1

There are a couple of ways to achieve this goal:

1) Utilize the "keypress" event. Monitor for specific characters like (|,@,#,$) and prevent their entry.

2) Implement the "onblur" event. Validate the input content once the element loses focus. Display a message if the content is invalid.

Important Note

The second approach is considered superior as it can detect invalid inputs even when a user pastes content.

Implementation of First Method

 function CheckTxtBox(e) {
        var evt = (e) ? e : window.event;
        var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
        if (//condition based on character codes) {
            return false;
        }
        return true;
    };

Implementation of Second Method

Within your onblur event, validate the textbox value using a regular expression.

Answer №2

function ValidateInput(e) {
    var key;
    document.all ? key = e.keyCode : key = e.which;
    return ((key > 64 && key < 91) || (key > 96 && key < 123) || key == 8 || key == 32 || (key >= 48 && key <= 57));
}

Your ASP control example:

<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onkeypress="return ValidateInput(event)"></asp:TextBox>

Answer №3

When it comes to validating keys or text input in edit controls, Regular Expressions come in handy. For a demonstration of how to use them, check out: where you can find examples of validation techniques.

Keep in mind that relying solely on browser-side validation is not recommended. It's crucial to perform server-side validation as well. This is important because JavaScript may be disabled in browsers, potentially allowing non-validated data to be sent to the server.

Answer №4

Successfully completed the task by restricting input to only uppercase letters (A-Z) and numbers (1-9). Grateful for all the assistance provided.

<asp:TextBox ID="txtAccountName" runat="server"
    Width="100%" CssClass="input" Enabled="False"  onkeypress="return isNumber(event);"></asp:TextBox>

// Javascript function to validate and prevent symbols input
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

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 keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

How can I create subarrays from an array in JavaScript/jQuery based on their individual counts?

Is there a way to transform an array into subarrays based on the count of their element values using either JavaScript or jQuery? For instance: var myArray=["a","b","c","a","a","c","b"]; The desired output after tallying the elements a, b, and c output ...

JQuery grid pagination bar mysteriously missing

I'm having an issue with a Jquery grid that is built on an HTML table. I've properly configured the grid properties, including implementing pager functionality with a page size of 10. However, I am unable to see the page up and page down buttons ...

Steps for activating chromedriver logging using the selenium webdriver

Is there a way to activate the chromedriver's extensive logging features from within the selenium webdriver? Despite discovering the appropriate methods loggingTo and enableVerboseLogging, I am struggling to apply them correctly: require('chrom ...

updating the observable array in rxjs after every iteration

I am facing an issue with updating the status of contracts in my UI. I have an Observable that contains an array of ContractDto, which is displayed in a table using an async pipe. The 'status' column for each contract initially shows 'not pr ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Invoking a function beyond the boundaries of an Angular application

The Angular code I have is structured within a single module and controller. app.controller('MainCtrl', function($rootScope, $http) { $rootScope.graph = {'width': '100%', 'height': 500}; $rootScope.rectangl ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...

Sorting through an array of objects using criteria from a separate array of objects

Currently, I am faced with the task of filtering an array of objects based on criteria from another array. Essentially, I am looking to refine a list based on filters selected by the user. To illustrate, let's consider my initial list of results: [ ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

In JavaScript, whenever there is an error for each variable A in B, it means that B is an array of arrays

I stumbled upon this code snippet: var B = []; var data = []; data.push("string"); // .... B.push(data); // ... for each (var A in B){ console.log(B); console.log(A); let obj = A[0].split("|", 3); console.log(obj[0]); ...

I aim to add and modify the quantity of a specific item ID

When the item id already exists, the quantity should be added to the incoming quantity. If the id does not exist, then insert the id and its quantity. Here is an example of what should be inserted into the table: if item_id=array(24,25); quantity=arra ...

The command "cordova" cannot be identified as a cmdlet

After running the npm command, Cordova was successfully installed on my system. The files and folders can be found in the directories %appdata%/npm and %appdata%/npm/node_modules. However, when attempting to use any Cordova command within the VS Code termi ...

Remove all HTML tags except for those containing a specific class

Looking for a regex that removes all HTML tags except the "a" tags with the "classmark" class For example, given this HTML string: <b>this</b> <a href="#">not match</a> <a href="#" target="_blank" ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

The padding on the button inside the v-card is not being applied as expected

I am facing an issue with the following code snippet: <v-card height="200"> <v-card-actions class="mb-0"> <v-btn flat color="orange">Share</v-btn> <v-btn flat color="orange">Explore</v-btn> & ...

Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, every ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...