0

Here I have an asp:TextBox, a RegularExpressionValidator and a ValidatorCalloutExtender.

My issue is: without the OnKeyUp event, it works fine, the TextBox is validated and becomes red when it's invalid.
But when I add the event, it stops validating, the textbox can have any text inside, and it will not become red.
Here's some code:

ASP.NET:

<asp:TextBox 
    ID="txtTelefone"
    runat="server"
    OnKeyUp="maskField(this, event)"
    Text="()-"
    MaxLength="14">
</asp:TextBox>
<asp:RegularExpressionValidator
    ID="RegularExpressionValidator_Telefone"
    runat="server"
    ControlToValidate="txtTelefone"
    ValidationExpression="(^\(\d{2}\)\d{4,5}-\d{4}$)|(^\(\)\-$)"
    Display="None"
    ErrorMessage="Invalid format!<br>Phone: (xx)xxxx-xxxx<br>Cel: (xx)xxxxx-xxxx">
</asp:RegularExpressionValidator>
<ajaxToolkit:ValidatorCalloutExtender
    ID="ValidatorCalloutExtender_Telefone"
    runat="server"
    TargetControlID="RegularExpressionValidator_Telefone"
    HighlightCssClass="txt-TextBox-Error"
    WarningIconImageUrl="~/Image/BackGroundAjax.png"
    PopupPosition="left">
</ajaxToolkit:ValidatorCalloutExtender>

JavaScript:

function maskField(textbox, event) {
    //MASK TO PHONE NUMBERS -> FORMAT (99)99999-9999 OR (99)9999-9999
    if (event.char.match(/[0-9()-]/) || event.which == 8 || event.which == 46) {
        var next = textbox.selectionStart;
        var text = textbox.value.replace(/\D/g, "");
        var ddd = text.substring(0, 2).replace(/\ /, "");
        var firstSet = text.length == 11 ? text.substring(2, 7) : text.substring(2, 6);
        var secondSet = text.length == 11 ? text.substring(7, 11) : text.substring(6, 10);
        textbox.value = "(" + ddd + ")" + firstSet + "-" + secondSet;
        if (textbox.value.charAt(next - 1).match(/\D/) && event.char.match(/[0-9()-]/))
            next++;
        textbox.selectionStart = next;
        textbox.selectionEnd = next;
        textbox.focus();
    }
}

EDIT: Update after receiving my first answer:
Sorry, but I need the OnKeyUp event because I need to identify the key that caused the event.

Lucas
  • 534
  • 1
  • 10
  • 29

1 Answers1

0

I think it should not be OnKeyUp instead OnTextChanged. You can refer it to this page onkeyup event asp.net

Community
  • 1
  • 1
Neil Villareal
  • 627
  • 9
  • 14
  • OnTextChanged doesn't allow me to send the event. I need to know what button was pressed. – Lucas Sep 10 '15 at 12:19