gabsferreira gabsferreira - 20 days ago 6
ASP.NET (C#) Question

Validate character amount, text length and decimal places from input using javascript

I am using a javascript to validate input from a textbox that's inside a ASPxGridView control(DevExpress component).

I am using this javascript code to validate it(thru OnKeyPress event):

function CheckKey(s, e) {
var key = ASPxClientUtils.GetKeyCode(e.htmlEvent);
var char = String.fromCharCode(key);
if (e.htmlEvent.shiftKey) {
if (!IsAvailableChar(char))
ASPxClientUtils.PreventEvent(e.htmlEvent);
} else
if (!(IsAvailableChar(char) || IsAvailableKey(key))) ASPxClientUtils.PreventEvent(e.htmlEvent);

return;
}

function IsAvailableChar(char) {
var AvailableChars = "0123456789,";
return AvailableChars.indexOf(char) != -1;
}

function IsAvailableKey(key) {

switch (key) {
case 46: //delete
return true;
break;
case 37: //left arrow
return true;
break;
case 39: //right arrow
return true;
break;
case 16: //shift
return true;
break;
case 188: //comma
return true;
break;
default:
return false;
break;
}


I use this to "block" some characters and it works fine.
But now I wanna do something a little bit more complicated: I don't want the user to input more than one comma in the textbox.

A little bit more complicated than that: the maxlength of this textbox is 6. I want it to allow two decimal places only and the maximum of three numbers before the decimal places.
For example:
I want it to allow these strings: "123,12", "45,32", "7,65", "9,6", "85,32", "94,1", "310,2".
I don't want it to allow these strings: "1,123", "125,789", "1234,2"

Any ideas on how I can do that?

Thank you!

Edit:

I tried to use the two regular expressions you guys told me to like this:

function CheckKey(s, e) {
var key = ASPxClientUtils.GetKeyCode(e.htmlEvent);
var char = String.fromCharCode(key);

var text = document.getElementsByName(s.uniqueID)[0].value + char;

var regEx = new RegExp("/^\d{0,3}(,\d{0,2})?$/");

if(regEx.test(text))
return;
else
ASPxClientUtils.PreventEvent(e.htmlEvent);

return;
}


However,
regEx.test(text)
is always returning false, even when the input matches the regular expression.

Another edit:

I changed the instantiation of the RegExp object in the code above from this:

var regEx = new RegExp("/^\d{0,3}(,\d{0,2})?$/");


To this:

var regEx = /^\d{0,3}(,\d{0,2})?$/


And now it worked, thank you!

Answer
/^\d{0,3}(,\d{0,2})?$/.test(textbox.value + char);

This will match any number with as many as three pre-decimal places. Optionally, it allows a decimal and up to 2 decimal places. Also matches the empty string, for ease of use. So this will check to make sure the resultant box matches.

An explanation of the regEx:

^

Start of string

\d{0,3}

0 to 3 digits (inclusive)

(...)? 

An optional group

,\d{0,2}

A comma followed by 0 to 2 digits (inclusive)

$

End of string.