Global methods in C# ASP.Net

2.3k views Asked by At

I´m using C# and ASP.NET for developing in Windows Azure.

I want to do a global Method to validate fields, my idea is to do a global Method like (for example in Site.Master)

static Regex dateRegex = new Regex("^\\d{2}/\\d{2}/\\d{4}$");
public boolean validate( string type, string stringToValdate)
{
  boolean valid = NO;
  if (type = "date")
  {
      Match m = fechaRegex.Match(stringToValdate);
      if(m.Success)
      {
            valid = true;
      }
  }

 return valid;
}

And then use it in another webform

using ????

Site.Master.validate("date",TextBox1.Text);
3

There are 3 answers

6
Aghilas Yakoub On BEST ANSWER

You can use Extension Method on Master Type

public static class Extension
{ 
    public static boolean Validate(this Master master, 
                                   string type, 
                                   string stringToValdate)
    {
      boolean valid = NO;
      if (type = "date")
      {
          Match m = fechaRegex.Match(stringToValdate);
          if(m.Success)
          {
                valid = true;
          }
      }

     return valid;
    }
}

Use Case :

using NamesPaceOfExtension;

Site.Master.Validate("date",TextBox1.Text);
0
James On

I would introduce my own custom static Validation class instead of making it a function in the Global.asax - that's more for global site configuration.

0
CodingWithSpike On

You could use a static class to put all your validations in 1 place, for example:

public static class Validation
{
  private static Regex dateRegex = new Regex("^\\d{2}/\\d{2}/\\d{4}$");

  public static boolean Validate(string type, string stringToValdate)
  {
    boolean valid = false;
    if (type = "date")
    {
        Match m = dateRegex.Match(stringToValdate);
        if(m.Success)
        {
          valid = true;
        }
    }

   return valid;
  }
}

Then you can call this from anywhere:

bool valid = Validation.Validate("date", "01/01/2012");

However, static classes and methods are convenient and easy, but harder to test. If you are doing a lot of unit testing, it is often easier to make a non-static class to do validation that implements some interface, and pass one in to every page request using a dependency injection framework. That is a bit more advanced of a topic though.


Also, unless you have to, you shouldn't really make 1 big "validate anything and everything" method, passing in the type as a string. It is against separation of concerns and single-responsibility principal. It is better to make separate methods for each type.