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: (3178)

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) &&

See other Scripts in Form validation

Submit Your Scripts:

System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.

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

[ Refresh Image ]