TrN
TrN

Reputation: 1250

ASPxTextBox KeyDown event

I have ASPxTextbox and I'm trying to prevent users to typing letters. So I have my control code:

<dxe:ASPxTextBox ID="phone" Text="" runat="server" MaxLength="18" Width="100px>
  <ClientSideEvents Validation="Validation" KeyDown = "SkipLetters"/>
  <ValidationSettings ErrorDisplayMode="ImageWithText" ErrorTextPosition="Bottom" ValidateOnLeave="true" />
                                                                                        </dxe:ASPxTextBox>

and JavaScript for SkipLetters:

function SkipLetters(s, e) {
 
        if (e.htmlEvent.keyCode <= 90 && e.htmlEvent.keyCode >= 65) {
            e.htmlEvent.returnValue = false;
        } 
   
}

I know when the letters are typing in but actually I don't know how to prevent it :) I've tried to var content = s.GetText() as first call in SkipLetters but it's too late, content is changed. So should I in if statement GetText, find letters and erase them or is there any possibility to prevent adding them to textbox content?

Upvotes: 1

Views: 9862

Answers (2)

TrN
TrN

Reputation: 1250

I found a solution. "Use the force trn!" if someone needs:

<dxe:ASPxTextBox ID="visiblePhoneNumber" Text="+48" runat="server" MaxLength="18"
     Width="100px">
     <ClientSideEvents Validation="PhoneNumberValidation" KeyPress = "CheckKey" />
     <ValidationSettings ErrorDisplayMode="ImageWithText" ErrorTextPosition="Bottom" ValidateOnLeave="true" />
     <ValidationSettings>
         <RegularExpression ValidationExpression = "[0-9\s\-\+\(\)]{9,18}" />
     </ValidationSettings>
 </dxe:ASPxTextBox>

JavaScripts:

function CheckKey(s, e) {
    var key = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    var char = String.fromCharCode(key);
    if (e.htmlEvent.shiftKey) {
        if (!IsAvailableChar(char))
            ASPxClientUtils.PreventEvent(e.htmlEvent);
    } else
    if (!(IsAvailableChar(char) || IsAvailableKey(key))) ASPxClientUtils.PreventEvent(e.htmlEvent);

    return;
}

function IsAvailableChar(char) {
    var AvailableChars = "0123456789+- ()";
    return AvailableChars.indexOf(char) != -1;
}

function IsAvailableKey(key) {

    switch (key) {
    case 8: //backspace
        return true;
        break;
    case 189: //minus
        return true;
        break;
    case 46: //delete
        return true;
        break;
    case 37: //left arrow
        return true;
        break;
    case 39: //right arrow
        return true;
        break;
    case 16: //shift
        return true;
        break;
    default:
        return false;
        break;

    }

}

Upvotes: 0

DevExpress Team
DevExpress Team

Reputation: 11376

Use the ASPxSpinEdit for this purpose. It was specially designed to allow the end-user to input only numbers.

Upvotes: 1

Related Questions