1

I have an annotated data model that looks something like this:

Public Class Task
    Public Property TaskID As Integer

    <Range(0, 999999999, ErrorMessage:="Please enter a valid number.")>
    Public Property EstimatedHours As Nullable(Of Decimal)
End Class

This correctly validates the Estimated Hours field, and displays the error message if a user enters anything that is not between the specified range. My issue with this, however, is that it is PASSIVE validation. It allows users to enter "asdasfs2312" and then hit submit.

What I would like is ACTIVE validation, i.e. an input field that completely prevents a user from entering letters at all. Is there a simple way to do this within ASP.NET? I haven't had any luck yet with HTML5 number input types nor jQuery UI spinners.

So far the only solution I've found is pretty hacky.

EDIT : Just to clarify, I have both client and server side validation. I am just looking for a way to actively prevent client side input in a restrict-as-you-input fashion to cut down on the time it takes for a user to submit the form and THEN receive an error message.

Community
  • 1
  • 1
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64

1 Answers1

3

You have to do this in javascript which is client side. ASP.NET is a server side.

function numOnly(e) {
    var key; var tf;
    if (window.event) // IE 
        key = e.keyCode;
    else if (e.which) // Firefox/Opera
        key = e.which;
    if ((key > 47 && key < 58) || (key == 8) || (e.keyCode > 36 && e.keyCode < 41) || (e.keyCode == 46) || (e.keyCode == 9)) return true;
    else return false;
}

now if you're using jquery, you can simply do this:

$('#EstimatedHours').keypress(function(e) { 
    return numOnly(e); 
});

Problem with this is that if the user has javascript disabled for some reason, it'll allow all characters. For situations like this, you'll have to do a server side check on your form POST function in ASP.NET

mnsr
  • 12,337
  • 4
  • 53
  • 79
  • Works pretty well in Chrome, but in firefox you cant use the arrow keys or delete. Also can't add decimal points. – ElliotSchmelliot Dec 12 '13 at 00:50
  • Thanks for your help, I think I might go this route for the time being until something else hits me in the face. – ElliotSchmelliot Dec 12 '13 at 01:03
  • 1
    a trick here to figure out what extra keys you want using the above code is to replace 'return numOnly(e)' with 'alert(e.keyCode)'. So that way you can add it to the numOnly() function for it to return true – mnsr Dec 12 '13 at 01:04