/    Sign up×
Community /Pin to ProfileBookmark

testing string for numbers

How can I check and see if a string has all the numbers(0-9) in it and return false if it does not? I have already tried these two methods:
string.match(pattern)
isNaN(parseInt(string))
I used the pattern /[0-9]/ and also /[0-9]/g. As far as the value in string goes, it could be anything.
Only problem is that both of these methods return the first element ([0]) in the string. If we have a mixed string, for example ‘5yu45’, it would return true (because first element is a number) and give us the false result, although the string does not contain all the numbers. Any suggestion.

to post a comment
JavaScript

16 Comments(s)

Copy linkTweet thisAlerts:
@duke_okcauthorNov 30.2006 — here is the code example:

[CODE]<html>

<head>

<title>String testing</title>
<script>

function checkWholeForm ()
{

var textString= ''
var idString = form.string.value;
var firstChr = idString.charAt(0);
var numPart = idString.slice(1);
var chrTest = /[uU]/;
var numTest = /[0-9]/g;


if (idString == "")
textString += "Error 1n"

else if (!(firstChr.match(chrTest)))
textString += "Error 2n"

else if (numPart == "")
textString += "Error 3n"

//Either use this or the next
else if (isNaN(parseInt(numPart)))
textString += "Error 4n"

else if (!(numPart.match(numTest)))
textString += "Error 5n"

else if (!((idString.length == 6) || (numPart.length == 5)))
textString += "Error 6n"

if (textString){
alert (textString);
return false;}
return true;
}
</script>
</head>
<body bgcolor="#FBFDFF">

<FORM name='form' action='/.....' method='post' target='_blank' onSubmit='return checkWholeForm(this)'>
<input type="text" name="string" />

<INPUT TYPE='submit' NAME='submit4' VALUE='Submit'>

</body>

</html>[/CODE]
Copy linkTweet thisAlerts:
@JMRKERDec 01.2006 — Will this work for you?
[code=php]
function IsNumber(str) {
var i = 0;
var v = true;
var sarr = str.split('');
for (i=0; i<sarr.length; i++) {
if ((sarr[i] < '0') || (sarr[i] > '9')) { v = false; } // anything outside range?
}
return v; // return true or false (or use 0 and -1 instead)
}
[/code]
Copy linkTweet thisAlerts:
@Arty_EffemDec 01.2006 — How can I check and see if a string has all the numbers(0-9) in it and return false if it does not?[/QUOTE]
[CODE]<SCRIPT type='text/javascript'>

function hasAllDigits(s)
{
for(var i=0; i<10 && s.indexOf(String.fromCharCode(i+48))!=-1; i++)
;
return i==10;
}

alert(hasAllDigits("0a12b34c56g78j9"));
alert(hasAllDigits("93cde210abfhj"));
alert(hasAllDigits("3578960142"));

</SCRIPT>[/CODE]
Copy linkTweet thisAlerts:
@mrhooDec 01.2006 — If you want details about the missing digits:
[CODE]function check10(str){
var n=10, A=[];
while(n>0){
if(!RegExp(--n+'').test(str))A.push(n);
}
if(A.length> 0) alert( 'You are missing '+A.sort());
else // (process valid string)
}[/CODE]


Or to just return true or false:

[CODE]function check10(str){
var n=10;
while(n>0){
if(!RegExp(--n+'').test(str)) return false;
}
return true;
}[/CODE]
Copy linkTweet thisAlerts:
@KorDec 01.2006 — Regular Expressions have a simple custom character which matches the [I]non-digits[/I]: [B]D[/B]

<i>
</i>&lt;script type="text/javascript"&gt;
var myStrings=['567y8','54-,.','1234'];
var i=0, s
while(s=myStrings[i++]){
alert(Boolean(!s.match(/D/)))
}
&lt;/script&gt;


On the other hand you may want to check if the string might be a decimal number, [I]integer or floated[/I] (so that the dots are allowed in floated numbers) In this case you may simple check whether the transformed string is a decimal number or not, using [B]Number()[/B] method.
<i>
</i>&lt;script type="text/javascript"&gt;
var myStrings=['567y8','54-,.','1234','12.50'];
var i=0, s
while(s=myStrings[i++]){
alert(Boolean(Number(s)))
}
&lt;/script&gt;
Copy linkTweet thisAlerts:
@duke_okcauthorDec 01.2006 — Thanks for all the suggestions. I just got to work and going through all of them. I will need sometime to test them to my specific needs. Will keep you posted.... just an FYI (for weather junkies ? )...We had a bad snowstorm in Oklahoma City and life here is at halt....

Duke
Copy linkTweet thisAlerts:
@duke_okcauthorDec 01.2006 — Thank you guys!! I tested all the suggestions and they work fine. My favorite was JMRKER suggestion because it was very easy to implement in my program. I appreciate your help; all suggestions were great.

All I do now is call the IsNumber function and pass it my string (NumPart). If IsNumber function returns false, I display a message, if not control is passed to next 'if else' statement. This is what my code looks like (after I made changes per JMRKER’s suggestion).

[CODE]<html>

<head>

<title>String testing</title>
<script>

function checkWholeForm ()
{

var textString= ''
var idString = form.string.value;
var firstChr = idString.charAt(0);
var numPart = idString.slice(1);
var chrTest = /[uU]/;
var numTest = /[0-9]/g;


if (idString == "")
textString += "Error 1n"

else if (!(firstChr.match(chrTest)))
textString += "Error 2n"

else if (numPart == "")
textString += "Error 3n"

//Change to original code
else if (!(IsNumber(numPart)))
textString += "Error 4n"

else if (!((idString.length == 6) || (numPart.length == 5)))
textString += "Error 6n"

if (textString){
alert (textString);
return false;}
return true;
}

function IsNumber(str) {
var i = 0;
var v = true;
var sarr = str.split('');
for (i=0; i<sarr.length; i++) {
if ((sarr[i] < '0') || (sarr[i] > '9')) { v = false; } // anything outside range?
}
return v; // return true or false (or use 0 and -1 instead)
}

</script>
</head>
<body bgcolor="#FBFDFF">

<FORM name='form' action='/.....' method='post' target='_blank' onSubmit='return checkWholeForm(this)'>
<input type="text" name="string" />

<INPUT TYPE='submit' NAME='submit4' VALUE='Submit'>

</body>

</html>[/CODE]
Copy linkTweet thisAlerts:
@JMRKERDec 01.2006 — You're welcome.

All the suggestions will do what you want to varying degrees of "neatness".

I just went with the KISS system for your initial posting.

BTW, for us in Florida, what is a snowstorm? Opposite of a heatwave? ?
Copy linkTweet thisAlerts:
@Arty_EffemDec 01.2006 — Thank you guys!! I tested all the suggestions and they work fine. My favorite was JMRKER suggestion because it was very easy to implement in my program. I appreciate your help; all suggestions were great.

All I do now is call the IsNumber function and pass it my string (NumPart). If IsNumber function returns false, I display a message, if not control is passed to next 'if else' statement.[/QUOTE]
Your error messages could be more informative, however could you explain how a function that detects a non-digit, can be used to detect the presence of all the digits 0-9?
Copy linkTweet thisAlerts:
@duke_okcauthorDec 02.2006 — I agree that messages should be more descriptive. I apologize, I was just trying to save some space. I am not sure which function are you referring to? Can you please post the name of the function here?

Duke
Copy linkTweet thisAlerts:
@Arty_EffemDec 02.2006 — I agree that messages should be more descriptive. I apologize, I was just trying to save some space. I am not sure which function are you referring to? Can you please post the name of the function here?

Duke[/QUOTE]
You asked to be able to [CODE]check and see if a string has all the numbers(0-9) in it and return false if it does not[/CODE]and it seems that you are using the function [I]IsNumber[/I] in an attempt to accomplish that task. Have I misunderstood, and if so what is your code attempting to validate?
Copy linkTweet thisAlerts:
@duke_okcauthorDec 02.2006 — function checkWholeForm ( ) calls another function ( IsNumber() ) and passes it the

string numPart as a parameter. The string numPart can contain any

character (0-9,a-z,A-Z, special characters and spaces).

Once the function IsNumbers is called, here is how it works:

  • 1. The var 'v' is set to 'true' initially

  • 2. We convert the numPart string into an array using split('') function. For example we

    have a string "my bad you are right". If we use the split('') function, it will give us back

    m,y, ,b,a,d, ,y,o,u, ,a,r,e, ,r,i,g,h,t which is an array of 20 starting ([0]) at m.

  • 3. Once we have the array, we use a for loop which determines the length of the array and

    repeats the loop that many times. Within the for loop, we check all the elements and if anything

    does not match our test ( which checks the elements to be from 0-9), we set the var v to

    'false' (which was set to true in first place).

  • 4. We return the value of v (either true or false) back to the calling function.


  • Once the calling function, checkWholeForm ( ), gets the value back, here is how it works:

  • 1. It negates the value to get the right effect. If false was returned, it becomes 'True' now

    and we display the error message and pass the control to the next 'if statement' in the sequence.

  • 2. If true was returned( which means no non-digit was found in string), negation makes it 'false. We

    do not display the error message and go to the next 'if else' statement in the sequence without passing control

    from current if statement to the next.


  • I hope it makes sense. The code is a complete example. Please feel free to test and play with it and let

    me know if you find anything otherwise.

    Duke
    Copy linkTweet thisAlerts:
    @Arty_EffemDec 02.2006 — [B][snip][/B]I hope it makes sense. The code is a complete example. Please feel free to test and play with it and let

    me know if you find anything otherwise.

    Duke[/QUOTE]
    I told you what [I]isNumber[/I] does, having discerned it in less time than it would have taken to read your explanation.

    Your code does not try to/need to perform the test that you requested originally.

    There is a considerable difference between testing for the presence of a non-digit and "check and see if a string has all the numbers(0-9) in it".

    I suggest that you learn how to write a clear specification.

    Your code appears to be testing for 'u' followed by five digits, in which case provided you don't need detailed error messages, it boils down to:
    [CODE]function checkWholeForm(str)
    {

    return /^ud{5}$/i.test(str.replace(/^s+|s+$/g,''));
    }[/CODE]
    Copy linkTweet thisAlerts:
    @so_is_thisDec 02.2006 — How can I check and see if a string has all the numbers(0-9) in it and return false if it does not?[/QUOTE]
    It has sortof been touched upon, but I wish to reiterate that the following is the simplest and most complete test for numeric data. I've given two forms -- (a.k.a., new methods for any string variable) -- one for digits-only and one for full numeric validity. The following will require a string of at least one digit but will validate for any number of digits in said string:
    [CODE]
    String.prototype.isDigits = function() { return /^d+$/.test(this.toString()); }[/CODE]

    The following will, likewise, require a string of at least one digit but will also allow a single (optional) decimal point and a single (optional) leading sign (which leading sign is what is supported when converting a string to a number):
    [CODE]
    String.prototype.isNumeric = function() { return /^[+-]?d+.?d*$/.test(this.toString()); }[/CODE]

    Note that these prototype methods are added to the String object because all form field values represent string data. Thus, these become automatically useful in field and form validation. For example:
    [CODE]
    if(document.formName.fieldName.value.isDigits())
    {
    alert("isDigits returned a true result.");
    }
    else
    {
    alert("isDigits returned a false result.");
    }[/CODE]

    Of course, if you want to get fancy, arguments to these new methods can allow you to specify the minimum and maximum number of digits to allow.
    Copy linkTweet thisAlerts:
    @duke_okcauthorDec 04.2006 — 
    Your code appears to be testing for 'u' followed by five digits, in which case provided you don't need detailed error messages, it boils down to:
    [CODE]function checkWholeForm(str)
    {

    return /^ud{5}$/i.test(str.replace(/^s+|s+$/g,''));
    }[/CODE]
    [/QUOTE]


    You nailed it down well. This is easier than what I have done in my code. I guess the only shortfall would be, like you mentioned, its inability to display detailed error messages (but we can always display generic message). Otherwise, it's perfect for what I have been trying to do. Thanks for all the suggestions...I feel the 'love' in the air ?

    Duke
    Copy linkTweet thisAlerts:
    @KorDec 05.2006 — Regular Expressions are a powerful weapon when dealing with strings. You should have a look:

    http://lawrence.ecorp.net/inet/samples/regexp-intro.php
    ×

    Success!

    Help @duke_okc 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,
    )...