简体   繁体   中英

What is the better way/place for validation?

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 ?

The asp.net website offers guidance for three cases:

These are probably worth reading before making any decisions.

Definitely worth reading up on the various options - choose whichever you think best suits your needs and style.

However, you will almost certainly end up creating a validation function on your service at some point to cope with business rules, so that may be the tie-breaker :-)

Heres a few extra links which may be useful too:

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