Be careful when validate input using length() in Javascript


This is trivial things but sometimes just happen. For instance we want to validate the input from users. Fyi, I use JQuery example here.

1
var amount = $(".amount p").text();

When we want to validate amount when we pass this variable into function, usually we use:

1
2
3
if(amount.length > 0) {
     // logic here
}

But, when we have amount in Integer or Float, then it will be problem, eg:

1
2
var amount = $(".amount p").text();
var amount = parseFloat(amount);

Using validation based on length will be failed. Instead of counting on string element length, we can use this validation:

1
2
3
if(amount) {
     // logic here
}

So, this the tricky part is how we validation javascript variable data type.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.