JavaScript - check for numbers in a text field

It takes in the value of a textfield, Im trying to have it so if any numbers are in the field then il be able to stop it.

 function hasNumbers(input) {

     var length = input.length;
     var end = 0;

     for (var x = 0; x < length; x++) {
         var char = input.substring(x, 1);
         trueFalse = isNaN(char);
         if (! trueFalse) {
             end++;
         }
     }

     if (end > 0) {
         return false;
     }

     return true;
 }

Answers


You can replace your function with this:

function hasNumbers(input) {
    return /[0-9]/.test(input);
}

/[0-9]/ constructs a regular expression that matches any numeric character.

Once you have a regex object, you can call test(s) to see if s matches the regex.

Here is more information about the RegExp.test() method.

Here is more info on regular expressions in general.

Here is a fiddle that shows the above code in action.

Here is another fiddle that shows the above function validating a text input.


Need Your Help

How to 'merge' a XAML file and its code-behind with Visual Studio

wpf visual-studio xaml code-behind

I have a template defined in a XAML file named 'MyTemplate.xaml'. This template is using a code-behind file named 'MyTemplate.cs'.

Where can I export AWS Cloudwatch Logs (for Loggly)?

logging amazon-web-services amazon-s3 amazon-cloudwatch loggly

I know they are storing them somewhere. Maybe a DynamoDB or S3 bucket?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.