/    Sign up×
Community /Pin to ProfileBookmark

Identifying data types

Hi all,

I’m currently working on a simple javascript programme and have hit a brick wall (surprise surprise…).

I need my programme to recognise when the user enters a non-numeric number, ie a word or even just gibberish. At the moment I am trying this conditional:

if (typeof(age_of_user) != Number) {
alert(‘Error. Please enter your age in numeric form.’);
}

This alert message appears no matter what the user has entered in the text box, leading me to suspect something has gone awry. Any clues?

Thanks folk,

Mike

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@Declan1991Nov 02.2008 — if (typeof age_of_user != "number") {
alert('Error. Please enter your age in numeric form.');
}
Copy linkTweet thisAlerts:
@MrNobodyNov 02.2008 — Actually, I don't think even the above will work. All [B]form[/B] and prompted user input is always in string format. Thus, the [B]typeof[/B] operator will never return "number" for those types of values even if they are purely numbers. The solution is to use other methods of validation -- [B]Regular Expression[/B]s or the [B]Number()[/B] object itself.
var num = Number(age_of_user);
if (isNaN(num)) {
alert('Error. Please enter your age in numeric form.');
}
Copy linkTweet thisAlerts:
@Declan1991Nov 02.2008 — Ya, MrNobody is right, it has to be converted to a number first, I presumed you did that. However, isNaN can take string as an input, so you actually don't need to convert for MrNobody's, while you do for mine.
Copy linkTweet thisAlerts:
@MrNobodyNov 02.2008 — What he meant by that is that you can do this:
[CODE]if (isNaN(age_of_user)) {
alert('Error. Please enter your age in numeric form.');
}[/CODE]

But I was just being explicit -- for teaching purposes.
Copy linkTweet thisAlerts:
@javascriptloverauthorNov 02.2008 — That's really interesting about form content being treated as a string Mr Nobody, thankyou very much.
Copy linkTweet thisAlerts:
@rnd_meNov 03.2008 — [CODE]var x = "5"
Number(x) == x // true


var x = "five"
Number(x) == x // false[/CODE]
×

Success!

Help @javascriptlover spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...