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

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

Angular 2's Observable does not directly translate to a model

While delving into Angular 2, I experimented with utilizing an observable to retrieve data from an API. Here's an example of how I did it: getPosts() { return this.http.get(this._postsUrl) .map(res => <Post[]>res.json()) ...

Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best. I am attempting to include a js file that imports json from an html .js import menus from '../json/menus.json'; (function () { function parseMenu(ul, menu) { fo ...

Having trouble setting up the next-auth login page and experiencing issues with the getProviders() function

Greetings to all fellow web developers, I am currently working on a Next.js application that utilizes next-auth for user authentication. I have set up the [...nextauth].js file in the "pages/api/auth" directory and a signin.js file in the "pages/auth/" di ...

Tips for successfully passing an object as a prop in nextjs

Struggling to understand how to pass an object as a prop using useState in Next JS. My javascript functions include a lorem ipsum generator, housed in a component called Paragraphs. This component requires two properties: Number of paragraphs Sentence le ...

Is it possible for a Jquery radio button to trigger an infinite loop?

When I click on a radio button, I want to receive an answer from the PHP file. However, when I use the radio button, the alert appears in an endless loop. Why does this happen and how can I make the alert display only once? I tried with just a regular but ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

What is the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

I crafted this dropdown menu, but for some reason, the selections aren't registering when clicked. Below is the code I used. Any assistance would be greatly appreciated!

Hi there, I need some help with getting my code to run properly. I've created a dropdown box using HTML and CSS, but it seems like there's an issue with the JavaScript portion as the options are not being selected. I've included a code snipp ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

The use of callback functions with Model.findOne() in Mongoose is now deprecated, and will result

Think about this: app.get("/posts/:postId", function(req, res) { const requestedPostId = req.params.postId; Post.findOne({_id: requestedPostId}, function(err, post) { res.render("post", { title: post.title, content ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

Guide to placing an image in a designated position

I am looking to achieve the following scenario: Whenever a user uploads an image, it should appear in one of the smaller boxes on the right. Subsequent image uploads by clicking on the big box should populate the other small boxes on the right. Please refe ...

Refreshing an AJAX call automatically in Knockout JS

Greetings everyone! I'm currently working on setting up a simple setInterval function to automatically refresh my data every minute. The line that is giving me trouble is: setInterval(incidentViewModel.fetchdata,60000); I also attempted this: windo ...

What is the process for resolving arguments in UI-Router's resolve function?

There seems to be a gap in my understanding of UI-Router and angular's documentation, so forgive me if this seems naive, but here goes: On http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider, there is an example resolve fu ...

Issue with Parsley validation not functioning as expected

I have implemented parsley.js to validate my form, but I am facing an issue when trying to validate a checkbox using the data-mincheck attribute. Below is the snippet of my code: <form data-validate="parsley"> <p>Please choose at least 2 ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

There was an issue with the parsing of the module in ansi-html 1:0 due to an unexpected character "#" at the beginning of the line

I've been delving into learning angular js. Whenever I try to run ng serve --open, I encounter the following error: ERROR in ./ansi-html 1:0 Module parse failed: Unexpected character '#' (1:0) You may need an appropriate loader to handle th ...