Yilmaz Paçariz
Yilmaz Paçariz

Reputation: 186

detecting a character in input box

if(document.form.user.value=='')

this is a javascript code which tests if it is empty input box,

but I need a piece of code which controls is there any character in input box? could anyone help me?

I mean any character like /, &, or any letter... or I can say any character which is not number!

Upvotes: 1

Views: 404

Answers (3)

Fabrício Matté
Fabrício Matté

Reputation: 70139

Add the negation ! operator to your if statement:

if (!document.form.user.value=='')

Will return true if the value is different than an empty string (that is, if it has any character).

Or simply add an else block to your current if..

if(document.form.user.value=='') {
    //empty value
} else {
    //not empty
}

Updated answer as per question/comment update:

Use a regex to match for non-number characters:

if (/[^\d]/.test(document.form.user.value))
    //contains a non 0-9 character

isNaN is another viable option, but it'd allow for some non 0-9 characters: float . and negative - values would be allowed.

Upvotes: 1

Alex
Alex

Reputation: 349

Check is value exist:

if($(input).val())

Or:

if($(input).val().length > 0)

Upvotes: 0

Guffa
Guffa

Reputation: 700192

You mean if there is one or more characters, i.e. not empty?

if (document.form.user.value != '')

or:

if (document.form.user.value.length > 0)

Upvotes: 1

Related Questions