Monday, March 14, 2016

Restrict the number of decimal places at a float and validate a datetime at a Razor form!

@model Airport.Core.Objects.Flight
<h1>Add a Flight</h1>
@using (Html.BeginForm("Add", "Flight", FormMethod.Post, new {id="form"}))
{
   <div>
      @Html.LabelFor(m => m.Duration)
      @Html.TextBoxFor(m => m.Duration)
      @Html.ValidationMessageFor(m => m.Duration)
   </div>
   <div>
      @Html.LabelFor(m => m.DepartureTime)
      @Html.TextBox("Date", null, new { @type = "date" })
      @Html.TextBox("Time", null, new { @type = "time" })
      @Html.TextBoxFor(m => m.DepartureTime, new { @class="displaynone" })
      @Html.ValidationMessageFor(m => m.DepartureTime)
   </div>
   <div>
      <input type="submit" value="submit" onclick="var fate = prepare(); return fate;" />
   </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() { });
   function prepare() {
      var floaties = $("#Duration").val().split(".");
      if (floaties.length !== 2) {
         $("span[data-valmsg-for='Duration']").html("Keep float small.");
         return false;
      } else {
         if (floaties[0].length > 2) {
            $("span[data-valmsg-for='Duration']").html("Keep float small.");
            return false;
         } else {
            if (floaties[1].length > 2) {
               $("span[data-valmsg-for='Duration']").html("Keep float small.");
               return false;
            } else {
               var datetime = $("#Date").val() + " " + $("#Time").val();
               if (datetime.length < 16) {
                  $("span[data-valmsg-for='DepartureTime']").html("Give a time.");
                  return false;
               } else {
                  $("#DepartureTime").val(datetime);
                  return true;
               }
            }
         }
      }
   }
</script>

 
 

The displaynone class just does what you'd expect.

.displaynone {
   display: none;
}

No comments:

Post a Comment