Products
Services
Contact Us

Scripts: C# :: Form Validation :: Library Article #6

Developer's Section

Validating Numbers using regular expresions in C#
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (1809)
Favorites:

Learn to validate an input field that requires numeric values using regular expressions in the C# language.

The function show below takes as argument a string and tries to figure out if the string is a number by using regular expressions. Common patterns are 34.56, 56, 1305, etc.
See Below:

 Code Snippet 1


//Include Regular Expressions at the top of your script
using System.Text.RegularExpressions;

private bool IsNumber(String strNumber)
{
  Regex objNotNumberPattern=new Regex("[^0-9.-]");
  Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
  Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
  String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
  String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
  Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");
  return !objNotNumberPattern.IsMatch(strNumber) &&
             !objTwoDotPattern.IsMatch(strNumber) &&
             !objTwoMinusPattern.IsMatch(strNumber) &&
             objNumberPattern.IsMatch(strNumber);


See other Scripts in Form Validation

Submit Your Scripts:

If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]