简体   繁体   中英

How do i validate classfields?

Is this a good aproach to making sure the fields has valid values for a database?

    internal class Customer
{

    private string _CustomerId;
    internal string CustomerId
    {
        get
        {
            return (_CustomerId==null?string.Empty:(_CustomerId.Length>20?_CustomerId.Substring(0,20):_CustomerId));
        }
        set
        {
            _CustomerId = value;
        }
    }}

Regards Sven

A cleaner technique would be to annotate your properties with validation attributes and use a library to validate the entities.

Examples include:

Then, depending on the library selected, your code would resemble:

public class Customer
{
    [StringLengthValidator(20)]
    public virtual string CustomerId { get; set;}
}

Your way of validating input is very brittle. You are excepting any possible input (for the CustomerId in this case) and sanitize it when it is requested. This might work in this basic scenario, but in a lot of cases you can't sanitize the input. You are basically correcting the mistakes of the user and making assumptions of what he intended. How will you do that with an mail address? For instance, must the mail address 'stevenhotmail.com' be converted to 'steven@hotmail.com' or to 'stevenhot@mail.com'. Besides this, there is also the possibility of a programming error. Would you want your program try to fix your own programming errors. This will give you headache. Or what will you do when two properties of the same entity have to be compared?

A better solution would be to allow the entity to become in an invalid state and check it's validity just before saving it to the database. When it's state is invalid, don't try to automatically correct the changes, but just throw an exception or communicate the errors back to the user.

There are multiple approaches of doing this. You can for instance implement an IsValid() method on each entity or use a validation framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM