Ben
Ben

Reputation: 187

How to do jquery validation on something that is equal to zero, but not when its null/empty

So I want to validate a textbox that I have, the user can leave this box blank which is fine. However if they enter the number 0 in it, I want an error message to appear. However if it say is it null, it validates as an error when it is empty as well.
I have done is it equal to "0" in quotes, however if they put more than one 0 it accepts it. So what can I do to validate to check if it is 0, but not null.
I tried loads, this is my latest try, but nothing works

    if (this.value == 0 && this.value != null){
    }


Thanks

What "Rhumborl" said works great :)

Upvotes: 1

Views: 1083

Answers (2)

Rhumborl
Rhumborl

Reputation: 16609

if (parseFloat(this.value) === 0) {
}

should work for decimals. you shouldn't need parseInt as well.

Upvotes: 1

José M. Pérez
José M. Pérez

Reputation: 3279

You could to something like:

if (parseInt(this.value, 10) === 0) {
}

in case of null or empty string it would return NaN.

Upvotes: 2

Related Questions