-2

I need to validate my c# model class.

[Required(ErrorMessage = "Comma Separated String Required")]
[RegularExpression(@"", ErrorMessage = "Invalid Comma Separated String.")]
[RegularExpression(@"", ErrorMessage = "Duplicate Code.")]
public string CommaSeparatedString { get; set; }

I just tried the following regex, but it is not working for me.

((\s+)??(\d[a-z]|[a-z]\d|[a-z]),?)+?$

In my case, CommaSeparatedString can be:

ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7 - Valid

ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7,ASAEW6 - Invalid - Duplicate ASAEW6

ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7, - Invalid - Comma at end

ASAEW1,ASAEW2,,ASA,S4,ASAEW5,ASAEW6,ASAEW7 - Invalid - No value between 2,3 comma

The above requirement should happen. Is there any possible way to check duplicates in comma-separated String? I need to show 'Duplicates code' error message if CommaSeparatedString consists of duplicates. How can I do this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68
  • Not a full answer, but I think FluentValidation library will work wonders here, where you can write your custom validation rules. With RegEx only you will not go far though, I think you need to write a bit of code to split the arguments and check their existence and if there are any duplicates – Sotiris Panopoulos May 09 '20 at 06:33

2 Answers2

2

I'm not a regex magician, but puzzled together something that might work for you here:

^((([A-Z]+\d*)(?!.*,\3\b)),)*[A-Z]+\d*$

So to visualize this:

Regular expression visualization

In steps:

  • ^((( - Start string ancor followed by three capture groups
  • [A-Z]+\d* - Third capture group must exist out of capitals (at least one) followed by as many digits as possible
  • (?!.*,\3\b) - Negative lookahead to make sure that previously found pattern will not have a duplicate further down the line.
  • ),)* - Closing group 2 followed by a comma and closing group 1 which then must occur * as many times as possible
  • [A-Z]+\d* - The last bit is repeating the same pattern we were looking for in group 3
  • $ - End string ancor

I'm not the best at explaining either but I hope it's clear enough and working (hoping backreferences are allowed within c# as I have no experience in that) =)

JvdV
  • 70,606
  • 8
  • 39
  • 70
  • Sir how can I return separate model validation for `Invalid Comma Separated String.` and `Comma Separated String Required` ? Thanks anyway your answer sir – Sachith Wickramaarachchi May 09 '20 at 07:09
  • @Adam, I wouldn't be able to help you with `c#` other that the above as the pattern should work for all 4 cases your have put up. Sorry if it's not helpfull. – JvdV May 09 '20 at 07:14
  • Thank u, sir. And sir can you please provide me another Regex to check 1.Comma at end 2. Comma at the beginning, 3. No value between commas. Because I planned to check the duplicate part without regex. – Sachith Wickramaarachchi May 09 '20 at 07:16
  • Please help me, sir, How can I write a regex to check only these three validation. 1.Comma at end 2. Comma at the beginning, 3. No value between commas – Sachith Wickramaarachchi May 09 '20 at 09:25
0

You can take a look at custom validations for your model, using either the ASP.Net (Core?) framework or the FluentValidation Nuget package.

For a solution depending only on the framework, I write a sample that might work for you or at least get you started:

public class MyModel : IValidatableObject
{
    public string CommaSeparatedString { get; set; }


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (CommaSeparatedString.EndsWith(","))
        {
            yield return new ValidationResult("Invalid Comma Separated String - Comma at end");
        }

        var splitCodes = CommaSeparatedString.Split(",");
        var setOfCodes = new HashSet<string>();
        foreach (var code in splitCodes)
        {
            if (code.Trim() == String.Empty)
            {
                yield return new ValidationResult("Invalid Comma Separated String - Missing Code");
                continue;
            }

            var added = setOfCodes.Add(code);
            if (!added) yield return new ValidationResult($"Duplicate Code: {code}");
        }
    }
}
Sotiris Panopoulos
  • 1,523
  • 1
  • 13
  • 18
  • I'm not using .net core. Thanks anyway – Sachith Wickramaarachchi May 09 '20 at 09:24
  • How can I write a regex to check only this three validation? 1.Comma at end 2. Comma at the beginning, 3. No value between commas – Sachith Wickramaarachchi May 09 '20 at 09:25
  • Why are you determined to handle this with regex? In the other answer you were provided with a solution with regex, but you need to separate your errors. The same code works on .NET 4.X by the way, that's why I added the Core in parenthesis, as I was not sure which framework you were using. – Sotiris Panopoulos May 09 '20 at 09:41
  • Just some tips though: First of all, if this is a new application, consider the possibility to migrate to .NET Core. Second, regarding the RegEx: Having your validation inside RegEx will be a huge pain to debug and change, it might be better to be more explicit and have the logic in code. There is a famous quote: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. – Sotiris Panopoulos May 09 '20 at 10:10