/    Sign up×
Community /Pin to ProfileBookmark

Need Help with Number Validation

I am validating that a field called “number” is entered on my form with the following javascript code:

function FormValidator(theForm) {
if (theForm.number.value == “”) {
alert(“Please enter number.”);
theForm.number.focus();
return (false);
}
return (true);
}

Can anyone help me with the code required to extend this validation to ensure that only numbers (0-9) are entered i.e. no alpha or other characters and no blank spaces. Additionally (but not as important) how can I ensure that at least 6 but no more than 10 numbers are entered.

Many Thanks
PaulB

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@NedalsDec 29.2004 — This uses a 'regular expression'
[size=1]
function FormValidator(theForm) {
if (!/d{6,10}/.test(theForm.number.value)) {
alert("Please enter number with 6 to 10 digits.");
theForm.number.focus();
return false;
}
return true;
}
[/size]
Copy linkTweet thisAlerts:
@CharlesDec 29.2004 — If you take something that doesn't look like a number and try to cast it as a Number, NaN will be returned. And NaN evaluates to false in the boolean context. Thus:

[font=monospace]<input type="text" onchange="if (!Number (this.value)) {alert(); this.value=''}">[/font]
Copy linkTweet thisAlerts:
@paulbauthorDec 29.2004 — Thanks so much - a real help !!!
×

Success!

Help @paulb 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...