Skip to content

Instantly share code, notes, and snippets.

@rflechner
Last active January 20, 2017 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rflechner/b6234cb15acb5ae3780c5028c38f282d to your computer and use it in GitHub Desktop.
Save rflechner/b6234cb15acb5ae3780c5028c38f282d to your computer and use it in GitHub Desktop.
MVC validation exemple
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace WebApplication1.Controllers
{
// It a DTO model
public class UserInfo
{
[Required]
[StringLength(60, MinimumLength = 3)]
public string Login { get; set; }
[Required]
[StringLength(maximumLength: 20, MinimumLength = 6, ErrorMessage = "Password length must be between 6 and 20.")]
public string Password { get; set; }
[Required]
[RegularExpression(@"^.*@.*$", ErrorMessage = "Invalid email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please specify a birth year")]
public int BirthYear { get; set; }
}
// Custom ActionResult
public class ApiError : ActionResult
{
private readonly ModelStateDictionary _model;
public ApiError(ModelStateDictionary model)
{
_model = model;
}
public override void ExecuteResult(ControllerContext context)
{
var errors = _model.Values
.SelectMany(v => v.Errors.Select(e => e.ErrorMessage))
.ToList();
var json = JsonConvert.SerializeObject(errors);
var outputStream = context.HttpContext.Response.OutputStream;
context.HttpContext.Response.StatusCode = (int) HttpStatusCode.BadRequest;
context.HttpContext.Response.ContentType = "application/json";
using (var w = new StreamWriter(outputStream))
{
w.Write(json);
w.Flush();
outputStream.Flush();
}
}
}
// Controller Extension
public static class ControllerExtensions
{
public static ActionResult ApiError(this Controller controller, ModelStateDictionary modelState)
=> new ApiError(modelState);
}
// Controller
public class UsersController : Controller
{
[HttpPost]
public ActionResult Save(UserInfo info)
{
if (!ModelState.IsValid)
return this.ApiError(ModelState);
return Json(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment