I'm creating a program in which I need to validate user input.
The User should be able to write float numbers and some letters like 'k' for thousand or 'm' for million. Allowed are: digits, and only one letter from the list(g,k,m,n,u) and only one '.' for decimal numbers. If user puts different sign, two letters from the list, two dots, follows letter by another sign - nothing displays in textbox.
What i did so far is not working at all. I cannot even create a list with allowed signs. How can i solve this? I've seen almost every page on the web about regexp..
function signFilter(e)
{开发者_Python百科
var keynum;
var keychar;
var numcheck;
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /[0-9GMkmpu.]/;
return numcheck.test(keychar);
}
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeydown Here is sample code for input. Nothing i try gives resonable result. (of course, i removed '!'from return).
Your regex is just testing the presence of one of the chars into [
and ]
. What you are trying to do is testing for the presence of any other char in the string.
I suggest you had a ^
sign like : [^0-9GMkmpu.]
, so you will be able to detect any wrong char in the string.
With the regex you wrote something like : aaaaaaaaakhhhhhhhhh will return yes.
From the code you provided, it looks like you are testing the string one character at a time. The code you have to only validates that correct letters are inputted, but as a whole, the final string created from the keypresses may not be in the format you expect.
For example, a string 123.123.321.m
are all valid characters, but the final string is not valid.
Basically, you need to add validation that checks the final string inputted.
A regexp like this could help you in validating the final string input.
numcheck = /^[0-9]*\.?[0-9]+[gkmnu]?$/
This regexp says
- optionally match 0-9
- next, optionally match a dot
- next, match at least one number
- the end of the string may end in one character from the set
/^[0-9]*[\.]*[0-9]*[Mkmpu]*$/
This one is quite flexible and handles sereval cases such as ".57m" "57" "57m" "57.m" "57.57m".
This works
http://jsfiddle.net/mplungjan/KvJQx/
window.onload=function() {
document.getElementById("t1").onkeypress=function(e) {
var keyNum = (window.event)?window.event.keyCode:e.which;
var keyChar = String.fromCharCode(keyNum);
return /[0-9GMkmpu\.]/.test(keyChar);
}
}
精彩评论