Technology Lover Technology Lover - 1 month ago 8
C# Question

How to fix this regex validation method?

I am a new C# developer and I am using

Regex
class for my first time.

As I am developing a validation class for my simple project, I am using Regex to develop a number of methods that will take care of user(s) inputs validation. I am struggling right now with developing a method that will validate the number of characters entered by the users against the limited number of characters that varies from one text field to another.

public void ValidateLength(string input, int count)
{
string regFormat = @"[a-zA-Z]{" + count.ToString() + "}";
string message = "";

Regex reg = new Regex(regFormat);
foreach (var regexMatch in reg.Matches(input))
{
message = regexMatch + "The maximum length is" + count;
}
}


Then, since I have the following TextBox in ASP.NET:

<asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBox2" runat="server"></asp:TextBox>


I am trying to use the validation method with those two TextBoxes, However, it doesn't work and I don't why:

Validate validate = new validate();
if(txtBox.Text.toString() != "")
{
if(validate.ValidateLength(txtBox.Text.toString(), 20)
{
//Do this stuff
}
}


Would you kindly help me in fixing/modifying this validation method in order to make it working with any
TextBox
and and specified length by the user?

Answer

I don't think you need to return the length back, You're the one who is passing it inside. Youknow it right?

public bool ValidateLength(string input, int count)
{
    string pattern = @"^[a-zA-Z]{0," + count.ToString() + "}$";
    return Regex.IsMatch(input,regFormat);
}

You're almost there your pattern was [a-zA-Z]{" + count.ToString() + "} this matches only when there is exactly n number of elements found not less than n.

So here is what I updated {0,n} matches zero to n number of elements in input string. ^ and $ ensures the start and end of the string.