2

I found class name validation method using CodeDOM from SE and I used it:

System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)

through this link:Is there a .NET function to validate a class name?

But, class names don't allow '.' (OEM period) where namespaces can be something like: System.Linq for example which allows '.'. Before going for options like Regex or loops for validating namespace names, I like to know whether there are any methods in .NET for this task.

EDIT:

Actual scenario is, I have a from. User can give a class name and a namespace from textboxes. For that class name and namespace I'll give a generated code. If user entered SomeClass as class name and Some.Namespace for namespace then the generated code will be:

namespace Some.Namespace   
{   
  class SomeClass{}   
}

For that i need to validate those two names user entering.

Community
  • 1
  • 1
Irshad
  • 3,071
  • 5
  • 30
  • 51
  • Have you looked at the second method in the `CodeGenerator` class: `ValidateIdentifiers()`? – svick Mar 07 '13 at 16:28
  • Yes @svick, But it's parameter asks for my entire CodeObject. i.e. `ValidateIdentifiers(CodeObject e)`. But I only need to test the string like I test the classname.... – Irshad Mar 08 '13 at 03:14
  • You can always create a temporary object for that: `CodeGenerator.ValidateIdentifiers(new CodeNamespace(namespaceName))`. – svick Mar 08 '13 at 08:11
  • Good point. But it's a void method. How can I validate it? There will be no return type. Can you please explain it to me. – Irshad Mar 08 '13 at 09:30

2 Answers2

5

I have tried a different approach and it works for me.

public bool IsValidNamespace(string input)  
        {  
            //Split the string from '.' and check each part for validity  
            string[] strArray = input.Split('.');  
            foreach (string item in strArray)  
            {                  
                if (! CodeGenerator.IsValidLanguageIndependentIdentifier(item))  
                    return false;  
            }  
            return true;   
        }
Irshad
  • 3,071
  • 5
  • 30
  • 51
0

You can use CodeGenerator.ValidateIdentifiers() for that.

If you don't want to check your whole tree, just one namespace name, you can create a temporary object for that:

CodeGenerator.ValidateIdentifiers(new CodeNamespace(namespaceName));

Per the documentation, if the identifier isn't valid, the method will throw ArgumentException.

svick
  • 236,525
  • 50
  • 385
  • 514
  • I also made a custom approach to this. Split the namespace with '.' and check each of it for `IsValidLanguageIndependentIdentifier(string value)`. And it works. – Irshad Mar 11 '13 at 05:37