[英]how to validate a text field in jsp using java script for accepting only dot and comma as special characters
I need to allow only numerics, dot and comma in a text field. 我需要在文本字段中仅允许数字,点和逗号。 If the user enters other special characters an alert needs to be thrown.
如果用户输入其他特殊字符,则需要引发警报。
Please find below the conditions: 请找到以下条件:
Thanks for your help. 谢谢你的帮助。
Here is a start for you: http://jsfiddle.net/KLyy8/1/ 这是您的起点: http : //jsfiddle.net/KLyy8/1/
Unless you tell us the exact specifics we won't know how to write the regular expression. 除非您告诉我们确切的细节,否则我们将不知道如何编写正则表达式。 Sounds like you want numbers with thousands separator and decimals.
听起来像您想要带千位分隔符和小数的数字。 But how many of each?
但是每一个呢? The fiddle above will work for numbers like this...
上面的小提琴将适用于这样的数字...
123,456.79 123,456.79
12,345.6 12,345.6
1,234.56 1,234.56
etc... 等等...
validate=function(){
var str = document.getElementById('test').value;
var patt = new RegExp("^[0-9]{1,3}\,[0-9]{3}\.[0-9]{1,2}$");
var res = patt.test(str);
alert(res);
}
If the field should contain only numeric values with decimal places (for exmaple 3.14
, 112358
or 9,81
), then you can use only one regex: 如果该字段应包含小数位(对于〔实施例仅数值
3.14
, 112358
或9,81
),那么你可以只用一个正则表达式:
function validateString(str){
if(str.match(^[0-9\.,]+$)){
return true;
}else{
return false;
}
However if you want to be precise you will probably want to limit the dots and commas to one, if I understand your situation correctly. 但是,如果您想精确一点,如果我正确理解您的情况,则可能需要将点和逗号限制为一个。
Regex for that can look like this 正则表达式可以看起来像这样
^[0-9]+(\.|,){0,1}[0-9]+$
That means it starts with a number ( ^[0-9]+
), then it may contain zero or one times one comma or dot ( (\\.|,){0,1}
) and then again ends with a number ( [0-9]+$
). 这意味着它以数字(
^[0-9]+
)开头,然后可能包含零或一个逗号或点( (\\.|,){0,1}
)的一倍,然后再次以数字( [0-9]+$
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.