Restrict comma in asp.net textbox

1.7k Views Asked by At

I want to restrict the use of comma in textbox. Initially the textbox is disabled and only when the user clicks on a related checkbox, the textbox is enabled.

Here is the code I have tried:

function checkForComma(keyCode) {
    if (event.keyCode == 188) {
        alert('Not allowed');
    }
}

And the EditorTemplate:

@Html.TextBoxFor(m => m.AddressLine1, @Model.isUsed ? 
    (object)new { @class = "form-control" } : 
    new { @class = "form-control", @disabled = "disabled", @onkeypress = "checkForComma(this);" })

@Html.ValidationMessageFor(m => m.AddressLine1)
1

There are 1 best solutions below

6
On BEST ANSWER

you forgot to place return false in your function. modify you function following

function checkForComma(event) {
    if (event.charCode == 44) {
        alert('Not allowed');
        return false;
    }else{
        return true;
    }
}

Also modify your html code as following

@Html.TextBoxFor(m => m.AddressLine1, @Model.isUsed ? 
    (object)new { @class = "form-control" } : 
    new { @class = "form-control", @disabled = "disabled", @onkeypress = "return checkForComma(event);" })