Sibusiso Shongwe Sibusiso Shongwe - 25 days ago 6
ASP.NET (C#) Question

Call to a java script function Regular Expression Validator to fail In asp.Net

I have a

<asp:RegularExpressionValidator>
that validates a text box but i also have a javascript function that prevents entering of non numerical values in the textbox. when use the expression validator it works fine but as soon as i add
onkeydown="return jsDecimals(event);"
to the text box to call the
jsDecimals()
function the validator doesn't work. What am I doing wrong??

asp Code

<asp:TextBox ID="TextBox2" runat="server" CssClass="form-control" CausesValidation="true" MaxLength="13" onkeydown="return jsDecimals(event);"></asp:TextBox>

<asp:Button ID="Button5" runat="server" Text="Retrieve" CssClass="btn btn-default" OnClick="Button5_Click"/>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" CssClass="tooltip-arrow"
ErrorMessage="ID must be 13 Numeric characters" ControlToValidate="TextBox2" ValidationExpression="^[0-9]{13}$">
</asp:RegularExpressionValidator>


JavaScript:

function jsDecimals(e) {

var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
if (!jsIsUserFriendlyChar(key, "Decimals")) {
return false;
}
}
else {
if (evt.shiftKey) {
return false;
}
}
}
return true;
function jsIsUserFriendlyChar(val, step) {
// Backspace, Tab, Enter, Insert, and Delete
if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
return true;
}
// Ctrl, Alt, CapsLock, Home, End, and Arrows
if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
return true;
}
if (step == "Decimals") {
if (val == 190 || val == 110) { //Check dot key code should be allowed
return true;
}
}
// The rest
return false;
}

Ted Ted
Answer

Your syntax is incorrect. Check my comment on your code below. You do not appear to be closing the function after return true; and you are ending up declaring the next function within the 1st one.

function jsDecimals(e) {

  var evt = (e) ? e : window.event;
  var key = (evt.keyCode) ? evt.keyCode : evt.which;
  if (key != null) {
    key = parseInt(key, 10);
    if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
      if (!jsIsUserFriendlyChar(key, "Decimals")) {
        return false;
      }
    } else {
      if (evt.shiftKey) {
        return false;
      }
    }
  }
  return true; // <-- what's this? is there supposed to be a closing bracket after this line?

  function jsIsUserFriendlyChar(val, step) {
  .
  .
  .
Comments