473,769 Members | 6,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Validating a string?

I am looking for a good referance on how to validate a string in C#.
Specifically have a string which will contain a postal code that may or may
not be in the US. I need to check this string to decide wheather it is in
the US or outside the US. I think all I really need to do is see if the
string meets the form of five integers. If it does then I will assume that
it is a US zipcode and if it does not then I will assume that it is outside
the US.

Anyways sorry for the long explination but all I really need is a good
referance on how to check the string to see if it is 5 integers or somthing
else.

Thanks, Jeff Griffin
Nov 15 '05 #1
8 10926
using System;
using System.Text.Reg ularExpressions ;

namespace ConsoleApplicat ion4
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.Write(" Enter a zip code: ");
string input = Console.ReadLin e();
// Be sure to allow for ZIP + 4 as well
Match match = Regex.Match(inp ut, @"^\d{5}(-\d{4})?$");
Console.WriteLi ne(match.Succes s);
Console.ReadLin e();
}
}
}

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
Nov 15 '05 #2
In article <uZ************ **@TK2MSFTNGP12 .phx.gbl>, sfajeff2
@hotmail.NOSPAM .com says...
I am looking for a good referance on how to validate a string in C#.
Specifically have a string which will contain a postal code that may or may
not be in the US. I need to check this string to decide wheather it is in
the US or outside the US. I think all I really need to do is see if the
string meets the form of five integers. If it does then I will assume that
it is a US zipcode and if it does not then I will assume that it is outside
the US.

Anyways sorry for the long explination but all I really need is a good
referance on how to check the string to see if it is 5 integers or somthing
else.

Thanks, Jeff Griffin

Hi Jeff,
I'll write some code in here, so you may check it for typos.

bool CheckZIP(string sZip)
{
bool bSuccess = false;

if (sZip.Lenght == 5)
{
int i;
try
{
i = Int32.Parse(sZi p); //contains only digits
//if we reach here, the string contains only
//digits, else, we'll be in the catch block
bSuccess = true;
}
catch
{
//nothing to do, just avoid exception
//the bSuccess is already false
}
}

return bSuccess;
}

Hope that helps.
Sunny
Nov 15 '05 #3
Zip codes are 5 integers in France, and probably in lots of other countries.
So, you should not use this criteria to infer the country. You should add
some UI to let the user select the country (if your app has a UI, of
course).

Otherwise the System.Text.Reg ularExpression is a good place to start, or you
could write a specialized method that tests the string length and its
contents.

static bool IsZip5(string s)
{
if (s.Length != 5)
return false;
foreach (char ch in s)
{
if (!Char.IsDigit( ch))
return false;
}
return true;
}

Bruno.

"Jeff Griffin" <sf******@hotma il.NOSPAM.com> a écrit dans le message de
news:uZ******** ******@TK2MSFTN GP12.phx.gbl...
I am looking for a good referance on how to validate a string in C#.
Specifically have a string which will contain a postal code that may or may not be in the US. I need to check this string to decide wheather it is in
the US or outside the US. I think all I really need to do is see if the
string meets the form of five integers. If it does then I will assume that
it is a US zipcode and if it does not then I will assume that it is outside the US.

Anyways sorry for the long explination but all I really need is a good
referance on how to check the string to see if it is 5 integers or somthing else.

Thanks, Jeff Griffin

Nov 15 '05 #4
In article <Oa************ **@TK2MSFTNGP09 .phx.gbl>, fr****@acadx.co m
says...
using System;
using System.Text.Reg ularExpressions ;

namespace ConsoleApplicat ion4
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.Write(" Enter a zip code: ");
string input = Console.ReadLin e();
// Be sure to allow for ZIP + 4 as well
Match match = Regex.Match(inp ut, @"^\d{5}(-\d{4})?$");
Console.WriteLi ne(match.Succes s);
Console.ReadLin e();
}
}
}

Perfect, I have to read more about that regex stuff ...

So, discard my other post :)

Sunny
Nov 15 '05 #5
Frank, Sunny, Bruno- Thank yall so much, that was exactly what I needed.

Frank - Do you know of a site (or book) that explains more about the
following and what it all means:

@"^\d{5}(-\d{4})?$");

This seems to work great for what I need, but I would like to learn more
about what all this means. I am in college and have not learned about any of
this yet and would like to learn some more if I ever need to use this kind
of thing again.

Bruno - That is a good point, I was unaware that france used 5 digit
zipcodes as well. I have been mostly dealing with Canada and the UK. If
anyone else reads this and is trying to do somthing similar I was able to
find a solution to this by calling a web service that validates a US zipcode
if it meets th 5 integer criteria. I know I could have just done this to
begin with to check, but since it is a webservice it produces a perforamance
penalty, thus I find it better to do the check for 5 integers first and then
if it meets that criteria I check it aginst the webservice. This negates the
performance penalty for those with a "zipcode" that does not conform to the
5 integer rule.

Again, Thank you all very much!

Jeff Griffin
Nov 15 '05 #6
Thus spake Jeff Griffin:
Frank - Do you know of a site (or book) that explains more about the
following and what it all means:

@"^\d{5}(-\d{4})?$");
Do what I did: use Google. ;)
This seems to work great for what I need, but I would like to learn
more about what all this means. I am in college and have not learned
about any of this yet and would like to learn some more if I ever
need to use this kind of thing again.


A search on "c# regex tutorial" yielded dozens of pages on the subject.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
Nov 15 '05 #7
Just what I needed, Thanks Frank! (I was trying to look up "validate C#
string" which returned some allright results, but a lot of the same article
over and over again, just a different sites).

Jeff Griffin
Nov 15 '05 #8
For a good book on Regular Expressions, take a look at "Mastering Regular
Expressions" by Jeffrey Freidl.
David

Nov 15 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2267
by: Brian Kedersha | last post by:
I found code for validating XML documents with the XML Schema cashed for rapid access. Example 3: Validating with XMLSchemaCache. http://msdn.microsoft.com/library/en-us/xmlsdk/htm/xsd_devgd_hdi_validate_5zzn.asp This code seems not to be working no matter I do to fix it. I receive the following errors.
1
4337
by: Christian | last post by:
Hi, I load an Xml-file "customers.xml" into a DataSet (works fine) but then how do I validate it against a schema (e.g. customers.xsd) ? my customers.xml: <?xml version="1.0" encoding="utf-8"?>| <customers xmlns="http://tempuri.org/customers.xsd"> <Customer ID="1000"> <FirstName>Greg</FirstName>
6
3407
by: Robert Reineri | last post by:
Hello, New to the XML world and .NET. I have what I believe to be a simple problem, but I have read the .NET docs till I'm blue in the face and still can't locate a simple example of how to accomplish this. I have two strings (C# string type). One of them contains an XML document. The other one contains a schema.
1
2976
by: Andy | last post by:
I am having some trouble validating XML using the XmlValidatingReader. I have created some xml and used the visual studio to generate the schema. So I am confident that the xml and schema match. The problem I am having is that the validation event fires for each node in the xml. It seems to be completely ignoring the schema that I have used. I'm wondering if I need to do something extra to tell the xml which schema to use.
2
2641
by: Joris Janssens | last post by:
I'm trying to write a program for validating XHTML 1.1-documents against the XHTML 1.1 DTD (which is actually the same as validating an XML-file) but I always get a "(404) Not found" error. This is the program itself : ******************************************************************** using System; using System.Xml; using System.Xml.Schema;
1
4245
by: Craig Beuker | last post by:
Hello, I am experimenting with this XmlValidatingReader and have a question about how it is working (or not working as would be the case) The sample documents and code are included at the end of the post. I am using VS.net 2003, .Net 1.1, Win2k Server I have a simple schema and a simple XML document.
2
2128
by: Chris Dunaway | last post by:
I have a form with a textbox and numerous panels, buttons and other controls. I have handled the textbox Validating and Validated events. The textbox will hold a filename. In the validating event, I check that the string in the textbox is a file that exists or whether or not the string is blank and display a message box in either case. I also call e.Cancel so that the value will be corrected. However, certain buttons on the form...
5
4817
by: ameen.abdullah | last post by:
Hi Guys, I have a textbox in windows form that should only accept alphabets, numbers, spaces and underscore. If the textbox contains anyother character it should display a msg at the time of validation.. Is there any funciton in vb.net for this? or any other way?? Waiting for ur replies...
1
3797
by: =?Utf-8?B?bGpsZXZlbmQy?= | last post by:
I've noticed that controls do not raise a Validating event if they are contained in a ToolStripDropDown via a ToolStripControlHost item. Please run the following sample and follow the instructions on the form to reproduce this issue: ------------------------------------ Public Class Form1 Inherits Windows.Forms.Form
6
4508
by: Richard | last post by:
I'm validating a date and time string which must be EXACTLY of the format yy-mm-dd hh:mm:ss and extracting the six numeric values using sscanf. I'm using the format string "%2u-%2u-%2u %2u:%2u:%2u" which works, but it allows each numeric field to be either 1 or 2 digits in length. Also the man page for sscanf says that preceeding white space before a numeric is ignored.
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10223
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.