views:

32

answers:

3

How can we do validation for percentage numbers in textbox . I need to validate these type of data

Ex: 12-3, 33.44a, 44. , a3.56, 123

thanks in advance sri

A: 

If you're talking about checking that a given text is a valid percentage, you can do one of a few things.

  • validate it with a regex like ^[0-9]+\.?[0-9]*$ then just convert that to a floating point value and check it's between 0 and 100 (that particular regex requires a zero before the decimal for values less than one but you can adapt it to handle otherwise).
  • convert it to a float using a method that raises an exception on invalid data (rather than just stopping at the first bad character.
  • use a convoluted regex which checks for valid entries without having to convert to a float.
  • just run through the text character by character counting numerics (a), decimal points (b) and non-numerics (c). Provided a is at least one, b is at most one, and c is zero, then convert to a float.

I have no idea whether your environment support any of those options since you haven't actually specified what it is :-)

However, my preference is to go for option 1, 2, 4 and 3 (in that order) since I'm not a big fan of convoluted regexes. I tend to think that they do more harm than good when thet become to complex to understand in less than three seconds.

paxdiablo
A: 

You can further optimize this expression. Currently its working for all given patterns.

^\d*[aA]?[\-.]?\d*[aA]?[\-.]?\d*$
Chinmayee
@chinmayee, think this is not validating 2 dots Ex: 1.2.3 I tested like tis var regexPattern = /^\d*[aA]?[\-.]?\d*[aA]?[\-.]?\d*$/; if(!regexPattern.test(str)) { alert("value out of range or too much decimal"); }
Srinath
In that case replace ? [which matched 0 or 1 occurrence] by * [which matched 0 or more occurrences]. Now ur expression will be ^\d*[aA]*[\-.]*\d*[aA]*[\-.]*\d*$
Chinmayee
A: 

Finally i tried a simple validation and works good :-(

function validate(){ var str = document.getElementById('percentage').value; if(isNaN(str)) { //alert("value out of range or too much decimal"); } else if(str > 100) { //alert("value exceeded"); } else if(str < 0){ //alert("value not valid"); } }

Srinath