Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

javascript - Currency validation

Please help with me writing a JavaScript Validation for currency/money field.

So please provide any regular expressions if u have :)

Also, for my region, don't need any currency symbols like '$' in the field.

Only decimals are to be included for validation as special chars., along with numbers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a regexp:

var regex  = /^d+(?:.d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
    alert("Number is valid");

If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:

var numStr = "123.20";
var numNum = +numStr; // gives 123.20

If the number string is invalid, it will return NaN (Not a Number), something you can test for easily:

var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
    alert("numNum is not a number");

It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2) to round to 2 decimal places. parseFloat is much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc") would yield 123.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...