Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validation of a property

Status
Not open for further replies.

sds814

Programmer
Feb 18, 2008
164
0
0
US
I was going thru a msdn tutorial and there was a property that was being validated in a class. Is the best practice to do this in a class or on the client side of a presentation layer?

I see the advantage of doing it in a class that you can reuse the code among web pages. I see the advantage of doing it on the client side of a presentation layer as faster performance.

Thanks!

Code:
   public string SSN
   {
      get { return this.uniqueSsn; }
      set { 
         if (Regex.IsMatch(value, @"\d{9}"))
            uniqueSsn = String.Format("{0}-(1}-{2}", value.Substring(0, 3), 
                                                     value.Substring(3, 2), 
                                                     value.Substring(5, 3));
         else if (Regex.IsMatch(value, @"\d{3}-\d{2}-\d{3}"))
            uniqueSsn = value;
         else                                                        
            throw new FormatException("The social security number has an invalid format.");
      }       
   }
 
there are 2 parts to this question: 1. where to validate and 2. how to validate.

where: client or server?
always validate on the server as you should never trust the user's input (response). client validation is a nicety that improves the user experience, but it doesn't replace server validation. you can also run a lot more validation on the server with ease that you can on the client. i like to use client validation for checked input like : required, data type, range values. for business logic I keep that on the server.

how:
this get's into where in the code you put the validation. I have used 2 different approaches.
1. attributes like those found in Castle.Validators or DataAnnotations
2. separate classes like the Fluent Validation project.
my approach looks like this.

each request to the server will build a specific DTO. I then create validation rules for this DTO. if the validation passes. I can use the DTO to load the domain model. make the updates and save the changes.

Jason Meckley
Senior Programmer

faq855-7190
faq732-7259
My Blog
 
Thanks for sharing Castle.Validators and DataAnnotations. Never knew these existed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top