I know it's answered, but I think the whole converting to char array is not needed. You
You can simplify it further to (based on original code):
// SNString?.Length == 16 -> Should be exactly 16 characters
// SNString?[3] == '-' -> the first dash should be in index number 3
// SNString?[12] == '-' -> the first dash should be in index number 12
// SNString?.Replace("-", "")?.Length == 14 -> if there is only 2 dashes, then removing them would result with length == 14, otherwise is false
return SNString?.Length == 16 && SNString?[3] == '-' && SNString?[12] == '-' && SNString?.SubstringReplace(13"-", "")?.Length == 3;14;
which would beis equivalent to :
if(SNString?.Length == 16)
{
if (SNString?[3] == '-' && SNString?[12] == '-' && SNString?.SubstringReplace(13"-", "")?.Length == 314)
return true;
}
return false;
You should check the length of the provided string, then apply the other validations. The
The string length will determine if you need to apply the other validations or not. if the string length == 16, if
if the string's length is not equal to 16, then surely it's not a valid format, otherwise.
if the string length == 16, then it's a valid format which needs to be validated. then
Then you just get the position of the first and last dashes. if they're in the correct position, then
then the first and, second part, and third parts should have the correct length. Then, then you justcan use Replace
to replace all dashes with empty string, and check the last partresult length, if the result is 14, then there were only two dashes, which is valid, otherwise is not valid.
Now, you can validate three parts XXX-XXXXXXXX-XXX
, if your characters group are all numbers (without the dashes),
then you can add something like ulong.TryParse(SNString?.Replace("-", string.Empty), out ulong result)
, if true, then they're all numbers, otherwise it's false.
Doing that, would avoid converting it to char array.
There is one thing that you should consider, if there is certain format for each characters group, you might need to use Regex
instead. For
For instance, if the first part should always contains letters only, or one digit with two letters ..etc. then
then the current validation process will provide a non-valid string. Also, you might consider adding a validation of English letters and Digits to avoid having some non-English inputs.
here is Regex
Regex example (for future reference) :