PageRenderTime 14ms CodeModel.GetById 7ms app.highlight 3ms RepoModel.GetById 2ms app.codeStats 0ms

/pigeoncms/Js/validateInput.js

http://pigeoncms.googlecode.com/
JavaScript | 83 lines | 59 code | 14 blank | 10 comment | 28 complexity | e9cfe7bff1a8106f75d2a1ed4aee8491 MD5 | raw file
 1// version: beta
 2// created: 2005-08-30
 3// updated: 2005-08-31
 4// mredkj.com
 5
 6function extractNumber(obj, decimalPlaces, allowNegative)
 7{
 8	var temp = obj.value;
 9	
10	// avoid changing things if already formatted correctly
11	var reg0Str = '[0-9]*';
12	if (decimalPlaces > 0) {
13		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
14	} else if (decimalPlaces < 0) {
15		reg0Str += '\\.?[0-9]*';
16	}
17	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
18	reg0Str = reg0Str + '$';
19	var reg0 = new RegExp(reg0Str);
20	if (reg0.test(temp)) return true;
21
22	// first replace all non numbers
23	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
24	var reg1 = new RegExp(reg1Str, 'g');
25	temp = temp.replace(reg1, '');
26
27	if (allowNegative) {
28		// replace extra negative
29		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
30		var reg2 = /-/g;
31		temp = temp.replace(reg2, '');
32		if (hasNegative) temp = '-' + temp;
33	}
34	
35	if (decimalPlaces != 0) {
36		var reg3 = /\./g;
37		var reg3Array = reg3.exec(temp);
38		if (reg3Array != null) {
39			// keep only first occurrence of .
40			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
41			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
42			reg3Right = reg3Right.replace(reg3, '');
43			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
44			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
45		}
46	}
47	
48	obj.value = temp;
49}
50
51
52function blockNonNumbers(obj, e, allowDecimal, allowNegative)
53{
54	var key;
55	var isCtrl = false;
56	var keychar;
57	var reg;
58		
59	if(window.event) {
60		key = e.keyCode;
61		isCtrl = window.event.ctrlKey
62	}
63	else if(e.which) {
64		key = e.which;
65		isCtrl = e.ctrlKey;
66	}
67	
68	if (isNaN(key)) return true;
69	
70	keychar = String.fromCharCode(key);
71	
72	// check for backspace or delete, or if Ctrl was pressed
73	if (key == 8 || isCtrl)
74	{
75		return true;
76	}
77
78	reg = /\d/;
79	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
80	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
81	
82	return isFirstN || isFirstD || reg.test(keychar);
83}