Search code examples
c#asp.netvalidationbusiness-logic

Validation code in .aspx.cs (codebehind) or BLL or Both?


I am trying to break some of my old habits of writing bad code. One of them is where to put validation code. I don't think validation should be in the presentation layer. Or there could be some validation there?

Here is an example of what I used to do

protected void SaveBtn_Click(object sender, EventArgs e)
{

  Item itm = new Item();
  itm.Name = txtName.Text;

  if(String.IsNullOrEmpty(itm.Name))
  {
     //reject
  }
  else
  {
     ItemBLL.Save(itm); //no more validation here
  }
}

OR

public class ItemBLL
{

   public static int Save(Item itm)
   {
      //no more validation in .aspx.vb
      if(String.IsNullOrEmpty(itm.Name))
      {
        //reject
      }
      else
      {
       //Save item
      }
   }
}

I have been using the first approach and I am thinking of switching to the second but I can't anticipate what the problem would be or the advantage of one over the other. Please advice is appreciated even for better approach

UPDATE: I agree that for the sake of the users simple validation (e.g. common mistakes) should be done in presentation (.aspx) (using javascript, jQuery).

Some business logic validation should also reside in the BLL for portability and reusability.

Does this mean we can skip validation in codebehind (.aspx.vb or .aspx.cs)?


Solution

  • Both is best, but the BLL is a must. Today your business class is only used by the one interface - the browser, but tomorrow maybe you may want a web service to also use that class. Then you will need all of the business rules to be in the class, not the web page. But a lot of rules you will want to test client-side in Javascript to provide a responsive interface. The example you give where the Name cannot be empty is a classic for testing in Javascript and not allowing the "Save" button to be enabled until the Name has a value. However, lets say the Name field has to be unique - this may not be something you want to validate client-side, and are willing to wait until it gets to the server.