3

i am using asp.net-mvc3 helpers and the jquery validation plugin (what comes out of the box when you use the templates (Create, Edit, etc . .) and i have a field called MiniPrice that is a dataType decimal?

so it validates on the client side that i enter a number in the textbox.

if i enter 1.25 it works fine. If i enter 0.75 it works fine, but if i enter .75 it give this validation error:

enter image description here

why does the jquery unobtrusive validation think .75 isn't a valid number?

I found this bug that was filed years ago on the jquery core site and it was closed as not a jquery core issue but rather a plugin issue.

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 2
    Similar/duplicate to http://stackoverflow.com/questions/3129150/jquery-validation-allow-number-without-the-leading-zero/4056007 – boflynn Aug 30 '11 at 01:00

1 Answers1

5

That appears to be how the validator behaves. I'd open an issue with jQuery to see if they can (or want) resolve it.

In the mean time, you can make your own validator method like so that it behaves as you would expect:

$.validator.addMethod('myValidateNumber', function (value) { 
    return /^(\d\.|\.)?\d+$/.test(value); 
}, 'Please enter a valid number');

This regex appears to do what you desire - there is likely a better way to write it as well. I am no regex master, but this should suffice.

Then just use myValidateNumber in the class of whatever you are validating. You can read more about extending jQuery validation here.

EDIT: To wire this in to MVC3 - take a look at this StackOverflow post: Perform client side validation for custom attribute.

Essentially what we are doing is creating our own validation for this, and you can apply your own attribute to the model.

EDIT 2: It appears that if you use validator.addMethod('number'..., it will change the default behavior of the numeric validation. This means you shouldn't have to change your MVC Model at all. So basically, adding this to your page load:

$.validator.addMethod('number', function (value) { 
    return /^(\d\.|\.)?\d+$/.test(value); 
}, 'Please enter a valid number');

Should resolve the problem.

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • it seems a bit crazy to me that i am the first one running into this issue. I am using the MVC3 helpers so i am not explicitally setting up any field level validation. can you explain a bit more (or send over a link) on how you would up the code you entered to the validation plugin. Also would i have to search for all places i have decimal fields or can i do this in one central place – leora Aug 30 '11 at 00:33
  • if you want multiple leading digits (i.e. 12.345) use this re instead: /^(\d*\.|\.)?\d*$/ – lambinator Jan 07 '12 at 02:33
  • Despite this coming after the duplicate question's answer, I found that - http://stackoverflow.com/a/4056007/11912 - to better match the current jQuery validation plug-in. – James Skemp May 21 '12 at 22:13