ElliotSchmelliot
ElliotSchmelliot

Reputation: 8362

ASP.NET MVC 4 Active Validation for Numeric Fields

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.

Upvotes: 1

Views: 736

Answers (1)

mnsr
mnsr

Reputation: 12437

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

Upvotes: 3

Related Questions