ASP.Net Framework 4.0
JQuery
Its pretty frustrating that ASP.Net does not have built in 'decimal only' validation for texboxes. I attempted to create my own using simple Javascript, but my requirement was too complex. I needed to implement the following restrictions:
- allow positive AND negative numbers (therefore numbers with a single '-' at the beginning, or with a single decimal point are allowed)
- Validation independant of cursor location - if a number has been entered and the cursor is moved to the beginning the user may enter a negative symbol
- No flash of invalid characters on keypress (so simple Javascript 'find & replace' won't work)
- Allow backspace, enter, left/right arrows and other non character keypress events
I eventually stumbled across a neat solution at http://brianjaeger.com/process.php
To implement it, I added the jquery.limitkeypress.js file to my solution. Any textbox which required this validation was assigned the class 'decimal.' In my master page's javascript file, I had the following code to apply the jQuery to any textbox with a class of 'decimal' (I was using my own regex expression which can be passes as a parameter to the JQuery library):
// ^ - start of string anchor
// (-)? - match a '-', optional
// \d* - match zero or more digits
// \. - match a '.'
// \d{0,decPlaces} - match up to specified num of dps
// )? - decimal points are optional
// $ - end of string anchor
$('.decimal').limitkeypress({ rexp: /^(-)?\d*(\.\d{0,4})?$/ });
No comments:
Post a Comment