What methods can be used to restrict user input to numbers and letters only?

Is it possible to restrict the input in my text field username without using regex? I want users to only enter numbers and letters, with no white spaces or special characters.

<div class="form-group has-feedback" ng-class="addUser.username.$valid ? 'has-success' : 'has-error';">
 <label class="control-label" for="username">Username</label>
  <input class="form-control" name="username" ng-model="user.username" required>
   <span class="glyphicon form-control-feedback" ng-class="addUser.username.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>

This section is from the controller.

$scope.users = [{
    username: "a"
}];

$scope.addUser = function(user) {
    $dialog.open({
        showClose: false,
        closeByEscape: true,
        template: 'views/user/user-user-add.html',
        controller: ['$scope', function($dialogScope) {
            $dialogScope.isLoading = false;
            $dialogScope.errorMessage = "";
            $dialogScope.title = "New User";
            $dialogScope.user = {
                username: ""

            };

I would appreciate any assistance on this matter. Thank you.

Answer №1

Follow this method

$(function() {
    $('#username').on( 'keydown', function( e ) {
        if( !$( this ).data( "value" ) )
             $( this ).data( "value", this.value );
    });
    $('#username').on( 'keyup', function( e ) {
        if (!/^[_0-9a-z]*$/i.test(this.value))
            this.value = $( this ).data( "value" );
        else
            $( this ).data( "value", null );
    });
});

Make sure to include the id="username" attribute in your textfield.

Check out the live demo here

Note

If you have multiple username fields, change id="username" to class="username" and update the Javascript to $('.username'). This will allow it to work on multiple textfields.

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

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Spin an object on a stationary axis

Is there a method to create a similar effect using CSS, JS, or GSAP? ...

Building an AngularJS Service with TypeScript that is Non-Singleton: A Step-by-Step Guide

I need help converting an AngularJS Typescript Service into a Non-Singleton. Can anyone provide guidance on how to achieve this? (Note: This is not the same as other questions that focus on achieving this in JS) I have included some simple pseudo code be ...

What is the best way to retrieve distinct objects based on LocId across all locations?

Encountering an issue while working on Angular 7: unable to return distinct or unique objects based on LocId. The goal is to retrieve unique objects from an array of objects containing all Locations. allLocations:any[]=[]; ngOnInit() { this.locationsServ ...

voting-app-powered-by-express-angular-node

Here are my two files for a simple voting app, but I'm facing an issue where the buttons are not increasing the count immediately. The counts only increase by one when the voting.html page is refreshed. Any assistance would be greatly appreciated. &l ...

Menu button is expanded without the need to click

The Bootstrap 5 button extends the default behavior and does not collapse. Here is the code: <nav id="header-nav" class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class= ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

Unable to expand Bootstrap navbar due to collapsing issue

I recently implemented a collapsed navbar on my website using bootstrap. However, I'm facing an issue where it does not open when clicking on the hamburger menu. After researching various solutions for this problem and trying them out, none of them s ...

Ways to extract the initial layer of information from a JSON document

I have a JSON file named movie.json stored externally, and it follows this format: { "action": [ { "id": "1001", "name": "Matrix" }, { "id": "1002", & ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Issue with the usage of section helpers in express-handlebars

I'm having trouble getting the section helper to function correctly. The content of login.hbs was parsed properly, but the js section was not parsed at all. I attempted using helpers within res.render() and directly including section() in engine(), bu ...

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

Various Issues Regarding Jquery Libraries

Here's a question on my mind... Currently, in my main file index.php, I have imported jquery 2.0.3 like this: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> The issue arises bec ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

Illustrate an element positioned beneath a child element within a different element

I am in the process of designing an overlay on a Google Map that resembles a real map placed on a table, using 2 pixel lines as creases above the map. This design does not significantly impact interactions with the map; only 6 out of 500 vertical lines are ...

Using Mongoose to insert a JavaScript object directly into the database

Recently, I've been working on POSTing a JS object through AJAX to the nodejs backend. My goal is to seamlessly insert this js object into my mongoose db without having to manually map each key to the schema. This is what I have currently (a bit clun ...

What sets array of middlewares apart from compose-middleware?

Someone recommended that I utilize the compose-middleware module in order to have an array of middlewares. After trying it out, I discovered that it works seamlessly with express.js: router.post('/editPassword', doAction ); var doAction = [ ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Unusual behavior observed during npm update operation

Just starting out with Angular and NPM, I have encountered a puzzling situation. I have two Angular-CLI projects. When I run npm update --save in one project, the dependencies (including @angular dependencies) are updated from version ^5.2.0 to ^5.2.3 in ...