RegularExpressionValidation - is there a better way to write this?

时间:2016-06-18 19:59:30

标签: c# asp.net regex

I have a textbox that the requirements are for it to be five numeric characters followed by 3 letters that will match what was selected in a dropdownlist. This is the way I'm having it check:

        protected void ddlLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlLegalEntity.SelectedItem.Text == "FID")
        {
            RegularExpressionValidator1.ValidationExpression = "^[0-9]{5}(FID)$";
        }
        else if (ddlLegalEntity.SelectedItem.Text == "FLM")
        {
            RegularExpressionValidator1.ValidationExpression = "^[0-9]{5}(FLM)$";
        }
        else if (ddlLegalEntity.SelectedItem.Text == "FOF")
        {
            RegularExpressionValidator1.ValidationExpression = "^[0-9]{5}(FOF)$";
        }

And then it continues with a few more else if.......

So if in ddlLegalEntity you select the choice FLM, then the textbox will have to equal five numbers followed by FLM.

Such as...

13423FLM

56543FLM

This code works fine, but I feel like there must be an easier way to code this. maybe I'm wrong and this is the easiest way, but I'm just curious.

1 个答案:

答案 0 :(得分:0)

Maybe something like:

     protected void ddlLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
{
     RegularExpressionValidator1.ValidationExpression = "^[0-9]{5}("+ddlLegalEntity.SelectedItem.Text+")$";
}

And better use string.Format( string, params) for this purposes;

        private static readonly string validationRegEx= "^[0-9]\{5\}({0})$";
        String.Format(validationRegEx, ddlLegalEntity.SelectedItem.Text);
相关问题