sue
sue

Reputation: 133

How to allow user to enter only number and letters?

I am aware of using regex, but is that possible to not use it? this is my text field username in the modal form. i want to allow user to enter only number and letter and no white space and special character included.

<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 is the controller part.

    $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: ""

            };

appreciate if anyone could help me.

Upvotes: 1

Views: 112

Answers (1)

Kakashi Hatake
Kakashi Hatake

Reputation: 3054

Do it like this

$(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 );
    });
});

Add id="username" attribute to your textfield as well please.

Live demo

Edit

If you have multiple username fields, instead of id="username" use class="username" and change the Javascript to $('.username'). So it would work on multiple textfields.

Upvotes: 1

Related Questions