C# – the better way/place for validation

asp.netasp.net-mvccvalidation

In my asp.net mvc application i have service layer, which operated with business object, pass its to repository layer and return to controller. No i can't decide where i need to validate object. First place – use data annotation validation with attribute of component model annotation in business objects class, for example:

[AcceptVerbs("POST")]
    public ActionResult Edit(Source src)
    {
        if(!ModelState.IsValid){            
            return View("EditSource", src);

        _sourceService.SaveSource(src);

        return RedirectToAction("Index");
    }

[MetadataType(typeof(Source.MetaSource))]
public class Source
{
    private class MetaSource
    {
        [Required]
        public string Name { set; get; }
        [Required]
        public string Url { set; get; }
    }

    public int? ID { set; get; }
    public string Name { set; get; }
    public string Url { set; get; }

    public Source()
    {
        ID = null;
    }

Second way – validate objects in service layer, by passing validation dictionary to service layer, for example:

 [AcceptVerbs("POST")]
    public ActionResult Edit(Source src)
    {
        if (!_sourceService.ValidateSource(src)){           
            return View("EditSource", src);

        _sourceService.SaveSource(src);

        return RedirectToAction("Index");
    }

public bool ValidateSource(Source srcToValidate)
    {
        if (string.IsNullOrEmpty(srcToValidate.Name))
            _validationDictionary.AddError("Name", "Name is required.");
        else
            if (srcToValidate.Name.Trim().Length == 0)
                _validationDictionary.AddError("Name", "Name is required.");

        if (string.IsNullOrEmpty(srcToValidate.Url))
            _validationDictionary.AddError("Url", "Url is required.");
        else
            if (srcToValidate.Url.Trim().Length == 0)
                _validationDictionary.AddError("Url", "Url is required.");

        return _validationDictionary.IsValid;
    }       

I think of create client side validation, and add localization to validation errors, also i need create custom rules with calls to database, etc. What pros and cons of this 2 way, or maybe I need choose another way ?

Best Answer

The asp.net website offers guidance for three cases:

These are probably worth reading before making any decisions.