Arcadian
Arcadian

Reputation: 1373

How to check user input for correct formatting

This is what i've come up with so far

private void CheckFormatting()
{
    StringReader objReaderf = new StringReader(txtInput.Text);
    List<String> formatTextList = new List<String>();

     do
     {
         formatTextList.Add(objReaderf.ReadLine());
     } 
     while (objReaderf.Peek() != -1);

     objReaderf.Close();
     for (int i = 0; i < formatTextList.Count; i++)
     {

     } 
}

What it is designed to do is check that the user has entered their information in this format Gxx:xx:xx:xx JGxx where "x" can be any integer.

As you can see the user inputs their data into a multi-line textbox. i then take that data and enter it into a list. the next part is where i'm stuck. i create a for loop to go through the list line by line, but i guess i will also need to go through each line character by character. How do i do this? or is there a faster way of doing it?

thanks in advance

Upvotes: 3

Views: 4097

Answers (4)

user347594
user347594

Reputation: 1296

Try this.

    if (!System.Text.RegularExpressions.Regex.IsMatch("your_text", "G[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2} JG[0-9]{2}"))
    {
        //Error!
    }

Upvotes: 1

Sonic Soul
Sonic Soul

Reputation: 24979

best practice is to validate user input as they are entering data and make it clear what the format should be in your input design.

you could add a series of text boxes for each numeric section separated by : , and than validate each textbox for numeric values.

i am guessing this is a asp.net Page? if yes, than you can make use of asp.net validators both on the client, and server.

i.e.

<asp:textbox id="textbox1" runat="server"/>
<asp:RegularExpressionValidator id="valRegEx" runat="server"
    ControlToValidate="textbox1"
    ValidationExpression="[0-9]*"
    ErrorMessage="* Your entry is not a valid number."
    display="dynamic">*
</asp:RegularExpressionValidator>

Upvotes: 1

FBSC
FBSC

Reputation: 201

Use a regex In your case, G\d\d:\d\d:\d\d:\d\d:JG\d\d should work (didn't test it) use the using System.Text.RegularExpressions namespace

Upvotes: 1

Vivian River
Vivian River

Reputation: 32410

Regular Expressions is the fast way to do it.

Upvotes: 1

Related Questions