I want to make sure the first 4 letters in a eight character code is a letter. Is there a function for that, or do I have to make my own.
you can add javascript/regex validation
regex
^[a-zA-Z]{4}.*
AFAIK there's no built-in function. A letter might mean different things according to user culture. If you mean ASCII letter you could test like this:
bool IsASCIILetter(char letter) {
return letter >= 65 && letter <= 90 && letter >= 97 && letter <= 122;
}
If it's the contents of an input control you want to validate, use a RegularExpressionValidator.
This case is probably simple enough to just use a RegEx, but for more complex validation I try to avoid RegExes as they are just too complex to debug. As somebody smarter than me said 'I had a problem which I solved with regular expressions. Now I have two problems'. Even if you are comfortable with regular expressions, the person who maintains your code might not be.
More explicit code is a lot easier to read and maintain:
bool IsValid (string code) {
if (code.Length != 8)
return false;
for (int i = 0; i < 4; ++i) {
if (!Char.IsLetter(code[i]))
return false;
}
return true;
}
How about Char.IsLetter?
It has 2 overrides: one where you pass it a char and one where you pass it a string and index.
2 options:
Option 1 - Check for it in your code-behind:
if (txtBox1.Text.Length >= 4 && txtBox1.Text.ToCharArray().Take(4).All(c => char.IsLetter(c)))
{
// success
}
else
{
// validation failed
}
You didn't state whether you're enforcing a length of 8 or it's optional and upto 8. You can add this check fairly easily.
Option 2 - Use a RegularExpressionValidator with an optional RequiredFieldValidator. If you decide to go this route you really should know exactly what you want to permit for the last 4 characters as this example below allows anything and only restricts the first 4 to letters. Also, again, this will differ if you wanted to enforce a length of 8 or not. This one below makes it mandatory; to make it optional to have 8 characters you would use "[A-Za-z]{4}(.{4})?" instead.
<asp:TextBox ID="txtBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvtxtBox1" runat="server" ControlToValidate="txtBox1" ErrorMessage="txtBox1 is required!" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revtxtBox1" runat="server" ControlToValidate="txtBox1" ValidationExpression="[A-Za-z]{4}.{4}" ErrorMessage="First 4 characters must be a letter!" Display="Dynamic" />
A RequiredFieldValidator is needed if you don't want to allow a blank entry since the RegularExpressionValidator alone won't prevent blank/whitespace entries. For more info see my answer here.