Link to home
Create AccountLog in
Avatar of dsk1234
dsk1234

asked on

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

Avatar of Dushyant Sharma
Dushyant Sharma
Flag of India image

use match with regular expression.
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

forgot the regex here itis
[0-9]{3}.[0-9]{2}
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

Avatar of dsk1234
dsk1234

ASKER

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



ASKER CERTIFIED SOLUTION
Avatar of Lo-Tan
Lo-Tan
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of dsk1234

ASKER

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
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
And put "txt1" instead of "myField"
Avatar of dsk1234

ASKER

Thank you so much Lo-Tan.
Avatar of dsk1234

ASKER

I appreciate you help.