Javascript decimal validation

I assigned decimal(3, 2) to the column data type in sql server 2005, so  I need  javascript  such that user should not be allowed other than this format ie 111.11.
Any help would be appreciated.

Thanks

dsk1234Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dushyant SharmaCommented:
use match with regular expression.
HainKurtSr. System AnalystCommented:
I am using js provided by:

http://mredkj.com/tutorials/htmljs.html

and then use it like
<input id=txtFI name=txtFI
onblur="extractNumber(this, DecimalCount, AllowNegative);"
onkeyup="extractNumber(this, DecimalCount, AllowNegative);"
onkeypress="return blockNonNumbers(this, event, AllowDecimal, AllowNegative);" />

hope it helps...
// version: beta
// created: 2005-08-30
// updated: 2005-08-31
// mredkj.com
function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	
	return isFirstN || isFirstD || reg.test(keychar);
}

Open in new window

Dushyant SharmaCommented:
forgot the regex here itis
[0-9]{3}.[0-9]{2}
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Lo-TanCommented:
Something like this should work in Firefox and IE.  The answer above doesn't limit your non-decimal places to three digits.

<html>
	<head>
		<title>Hello</title>
	</head>
	<script type="text/javascript" language="JavaScript">
		var validateField = function(field, regex){
			var errorDiv = document.getElementById("errorMsg");
			if (!regex.test(field.value)){
				field.value = "";
				errorDiv.innerHTML = "Invalid value.";
			} else {
				errorDiv.innerHTML = "Thanks!";
			}
		};
		
		var addValidator = function(fieldId, regex){
			var field = document.getElementById(fieldId);
			var onBlurValidator = function(){
				validateField(field, regex);
			};
			if (field.attachEvent){
				field.attachEvent("onblur", onBlurValidator);
			} else {
				field.addEventListener("blur", onBlurValidator, false);
			}
			
		};
		
		var initPage = function(){
			// 'myField' is the id of the input element we are validating
			addValidator("myField", /^\d{3}\.\d{2}$/);
		}
	</script>
	<body onload="initPage();">
		<input type="text" value="" id="myField"><span id="errorMsg" style="margin-left: 20px;">Please enter a value.</span>
</html>

Open in new window

dsk1234Author Commented:
Hi ,

Thank you all  for your solutions.Based on the above solutions I tried this java script ie.

function decimaltest()
   
     {    
          var txt=document.getElementById("TextBox1").value;

         if (txt.match(/^\d{0,6}(\.[0-9]{2})?$/))
 
             {
       
           alert("ok")
       
           }
    else
      {
       alert("error")
      }

    }

The above code is working  fine except it is allowing more than 3 digits before decimal point ie 1111.11.

Actually I am looking for java script for the below formats.If user enters decimal, then he should be allowed only in  this format 111.11 (before decimal 3 digits and after decimal 2 digits must) other than this format not allowed.

1)111111-Allowed (max 6 digits)
2)11111-Allowed
3)1111-Allowed
4)111-Allowed
5)11-Allowed
6)1-Allowed
7)111.11-Allowed
8)11.11-Not allowed (since 2 digits before decimal)
9)1.1-Not allowed
10)111.111-Not allowed(since 3 digits after decimal)

Thanks



Lo-TanCommented:
Instead of writing a somewhat complex regular expression, it's probably better to do two different evaluations.

expr1 = /^\d{3}\.\d{2}$/;
expr2 = /^\d{0,6}$/;

if (expr1.match(value) || expr2.match(value)){
} else {
  // error
}

Open in new window


If you need one expression, I can probably come up with it.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dsk1234Author Commented:
Hi ,

I tried the above mentioned javascript ,but i am getting error. Is there anything i am missing  in the below java script?

function testdecimal()
    {
   
    var txt=document.getElementById("txt1").value;  //getting text box value
    var expr1 = /^\d{3}\.\d{2}$/;
    var expr2 = /^\d{0,6}$/;

    if (txt.match(expr1) || expr2.match(expr2)) //comparing user entered value with regular expressions
              {
               alert("ok");
              }
              else
              {
               alert("not ok");
               }
    }

Thanks
Lo-TanCommented:
Here is fixed code:

function testdecimal()
    {
   
    var txt=document.getElementById("myField").value;  //getting text box value
    var expr1 = /^\d{3}\.\d{2}$/;
    var expr2 = /^\d{0,6}$/;

    if (txt.match(expr1) || txt.match(expr2)) //comparing user entered value with regular expressions
              {
               alert("ok");
              }
              else
              {
               alert("not ok");
               }
    }

Open in new window


Note that you had txt.match and expr2.match   I think you want it to both be txt.match and txt.match taking different expr objects.
Lo-TanCommented:
And put "txt1" instead of "myField"
dsk1234Author Commented:
Thank you so much Lo-Tan.
dsk1234Author Commented:
I appreciate you help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.