Monday, March 14, 2016

Use Data Annotations in tandem with the validate/unobtrusive thing to prevent angle brackets from being passed in a form in the MVC paradigm.

This controller is silly and does not save submissions, but just squint your eyes and pretend it's not silly for now. This isn't the important part.

using System.Web.Mvc;
using Airport.Core.ExternalDependencies;
using Airport.Core.Objects;
namespace Airport.Mvc.Controllers5
{
   public class FlightController : Controller
   {
      private IFlightRepository _flightRepository;
      
      public FlightController(IFlightRepository flightRepository)
      {
         _flightRepository = flightRepository;
      }
      
      public ActionResult Index()
      {
         return View();
      }
      
      public ActionResult Add()
      {
         return View();
      }
      
      [HttpPost]
      public ActionResult Add(Flight flight)
      {
         return View(flight);
      }
   }
}

 
 

Alight, you do not want to do validations like this, instead you want to use data annotations. That allows for regular expressions. A model may be dressed up like so, and note the very different way (from this) in which I handled the double quote.

using System.ComponentModel.DataAnnotations;
namespace Airport.Core.Objects
{
   public class Flight
   {
      public float Duration { get; set; }
      [Required(ErrorMessage = "Don't leave whatever blank.")]
      [RegularExpression(@"^([a-z]*[A-Z]*[0-9]*[\.]*[\s]*[\']*[""]*[?]*[!]*[-]*[=]*[\*]*[:]*[;]*[,]*
            [\\]*[/]*[{]*[}]*[|]*[\[]*[\]]*[\(]*[\)]*[+]*[`]*[~]*[@]*[_]*[#]*[\$]*[%]*[\^]*[&]*)*$",
            ErrorMessage = "Don't put angle brackets in whatever.")]
      public string Whatever { get; set; }
   }
}

 
 

The last thing I have to share below is my view. I think you can see how one cannot hand angle brackets in for Whatever, but beyond this one cannot hand angle brackets in for Duration either as Duration will validate against a float type datapoint and floats don't have angle brackets floating within them. Duh.

@model Airport.Core.Objects.Flight
<h1>Add a Flight</h1>
@using (Html.BeginForm("Add", "Flight"))
{
   <div>
      @Html.LabelFor(m => m.Duration)
      @Html.TextBoxFor(m => m.Duration)
      @Html.ValidationMessageFor(m => m.Duration)
   </div>
   <div>
      @Html.LabelFor(m => m.Whatever)
      @Html.TextBoxFor(m => m.Whatever)
      @Html.ValidationMessageFor(m => m.Whatever)
   </div>
   <div>
      <input type="submit" value="submit" />
   </div>
}
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/javascript">
   $(function() {
   
   });
</script>

No comments:

Post a Comment