0

I've got a simple conditional that checks if an id is equal to something and also checks if it is a number. I'm also using isNumeric with a combination of .length. But for some reason the isNumeric part is not working as I can enter a string of letters and it doesn't validate. Any ideas?

var $this = $(this);
if(this.id == "userName" && $.isNumeric($this.val()).length < 10 ){
  //do something
}

1 Answer 1

7

The reason you're having problems is that this:

$.isNumeric( $this.val() )

returns true or false, and checking the length of a boolean makes no sense, as true or false will never have a length over 10, as booleans does'nt have a length, and returns "undefined" ?

Maybe you meant this :

if (
    this.id == "userName" 
    && 
    $.isNumeric( $this.val() ) 
    && 
    $this.val().length < 10 
   ){
      // do something if the value is numeric, and the string length is under 10
   }
Sign up to request clarification or add additional context in comments.

4 Comments

thanks @adeneo it's odd but I'm still getting the same results. If I input: **$.isNumeric( $this.val() ) ** as a letter it's not validating.
Not sure I get it, as a "letter" how exactly. You're only allowing numbers, like 434243 ?
Try replacing the isNumeric line with /\D/g.test(this.value)
It's a regex to check that the string contains only numbers, the same thing isNumeric is supposed to do internally ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.