Date DataAnnotation validation attribute not working - shows the time - asp.net-mvc

Not working. Date comes back from a database field. Shows as:
When it is not set from a database as there is no birth date, I get a little red dot top left. Shows as:
I don't want the time included. I have a data annotation display format but it does not seem to take affect.
My Model(not showing other fields) is:
using System;
using System.ComponentModel.DataAnnotations;
namespace GbngWebClient.Models
{
public class UserProfileForMaintViewModel
{
// Can be null.
[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[RegularExpression(#"(((0[1-9]|1[0-2])\/(0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public DateTime BirthDate { get; set; }
}
}
My view (not showing other fields) is:
#model GbngWebClient.Models.UserProfileForMaintViewModel
<h1 class="page-header">User Profile Maintenance</h1>
#{
ViewBag.Title = "UserProfileMaint";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading">Your Profile</div>
<div class="panel-body">
<div class="row">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.BirthDate, new { #class = "manadatory" })
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
</div>
<div class="col-md-3"></div>
</div>
<div style="margin-top:10px;"></div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}

From my previous experience I found out that it is much easier to deal with a string than a DateTime variable. So I usually use it as a hack. You can have an extra text field in your ViewModel and format it from the controller for the view -
public ActionResult Custom2()
{
var profile = new Profile();
profile.DoB = DateTime.Now.Date;
profile.DoBText = profile.DoB.ToString("yyyy-MM-dd");
return View(profile);
}
Now the view can accept the text data without any problem
#model mvcDeploymentTest.Models.Profile
#{
ViewBag.Title = "Custom2";
}
<h2>Custom2</h2>
#using (Html.BeginForm("PostTest", "Home", FormMethod.Post))
{
#Html.TextBoxFor(model => model.DoBText, new { #class = "form-control", Type = "date" })
<input type="submit" value="Submit" />
}
And once posted, you can parse the changed text value to datetime again with any formatting you want
[HttpPost]
public void PostTest(Profile myProfile)
{
DateTime dateValue;
if (!string.IsNullOrEmpty(myProfile.DoBText))
{
DateTime.TryParseExact(myProfile.DoBText,"yyyy-MM-dd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateValue);
myProfile.DoB = dateValue;
}
return;
}

ApplyFormatInEditMode is only used/applied when using EditorFor - you have to use the overload for TextBoxFor which accepts a format string in order to get a formatted output in the rendered <input />.
#Html.TextBoxFor(model => model.BirthDate, "{0:d}", new { #class = "form-control" })
{0:d} will apply whatever short date format matches your app's culture settings. Replace that with a custom format string if you want something else.
If you want to use your browser's native date input (<input type="date" />), you'll need to use an ISO-8601 short date, which is YYYY-MM-DD. An example:
#Html.TextBoxFor(model => model.BirthDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
The default modelbinder knows how to transform that into a DateTime object, which you can then format into whatever else you wanted/needed.

Related

How to validate the HTML controls with data annotations in MVC?

In .Net MVC. I have a html control. Inorder to bind it with the model property I am using name attribute. How do we get the validations(using data annotation) provided in the model class property into the html control?
In Cshtml
#using (Html.BeginForm("ClaimWarranty", "WarrentyClaim", FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
<div class="form-group row">
<label for="" class="col-md-2 col-form-label input-label">Email Address:</label>
<div class="col-md-8">
<input type="text" name="Emailaddress" class="form-control input-style" placeholder="example#company.com">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" onclick="ValidateFileSize()" class="btn btn-default" />
</div>
</div>
}
//The model class is below;
public class ClaimWarranty
{
[Required(ErrorMessage = "Email ID is Required")]
[DataType(DataType.EmailAddress)]
[MaxLength(50)]
[RegularExpression(#"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Emailaddress { get; set; }
}
I am using the name property to bind the text box to the model property .
<input type="text" name="Emailaddress" class="form-control input-style" placeholder="example#company.com">
How do I get the validations in the html control ,provided in the model class (using the data annotations) as shown above without using jquery validations or razor code?
In View
#model Demo.Models.Student
#using (Html.BeginForm("SaveStudent", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model =>model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btnbtn-primary" />
</div>
</div>
}
In Model
public class Student
{
[Required(ErrorMessage = "Please enter name"), MaxLength(30)]
public string Name { get; set; }
}
By default, ASP.Net MVC framework executes validation logic during model binding. In Controller side, we need to check
if (ModelState.IsValid)
{
}
OR We can also check Individual validation, as shown below:
if (ModelState.IsValidField("LastName") == false)
if(!ModelState.IsValid)
{
// you can get the error information from model state, convert it into list
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
// now you have got the list of errors, you will need to pass it to view
// you can use view model, viewbag etc
ViewBag.ErrorList = validationErrors;
return View();
}
else
{
// perform your business operation, save the data to database
return View();
}
On View Page -
you have to add check for validation error list
if(ViewBag.ErrorList != null)
{
foreach(var errorMessage in ViewBag.ErrorList)
{
// here you can display the error message and format in html
}
}
Way you can display error on view page
1. #Html.ValidationSummary() - It will display summary of the validation errors
2. #Html.ValidationMessageFor(x => x.Emailaddress) - It will display error message
for specific property
3. you have to manually retrieve the error information from model state and then store it in list and pass to the view page.

ASP MVC Validation

I need to perform validation on a textbox and Dropdown which triggers only when both the values are empty and does nothing when one of the value is empty. How would i implement it? Do i need to create a custom validator? Below is my Model and View
Model
public class CustomValidators
{
[Required]
[Required(ErrorMessage = "State Required")]
public string drpStateId { set; get; }
public System.Web.Mvc.SelectList drpState { set; get; }
[Required(ErrorMessage ="Region Required")]
public string txtRegion { set; get; }
}
View
#model InterviewTest.Models.CustomValidators
#{
ViewBag.Title = "Custom Validator";
Layout = "~/Views/_Layout.cshtml";
}
<p>#Html.ActionLink("< Back", "Index")</p>
#using (Html.BeginForm("CustomValidatorPost"))
{
#Html.ValidationSummary()
<div class="container-fluid">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#Html.DropDownListFor(c => c.drpStateId, Model.drpState, "", new { #class = "form-control" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(x => Model.txtRegion, new { #class = "form-control" })
#*<input type="text" id="txtRegion" name="txtRegion" class="form-control" />*#
</div>
</div>
<div class="col-sm-3">
<button type="submit" name="btnSubmit" id="btnSubmit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
There is no out of the box validation that works on 2 fields except for the compare validator, so in your case you have to create a custom validation.
You can create a JavaScript function and fire it on onchange on both the two text boxes and within it check the values and if both are empty, show an error message and prevent the form from being submitted, you can achieve that using JQuery validation by adding a custom validator, see this link for more details https://jqueryvalidation.org/jQuery.validator.addMethod/
On Server side, you can do a simple if statement in the controller action to validate that both the values are not empty and if both are empty, then add an error to the ModelState

What is the preferred way to standardise complex html views for data types?

I have code like this that I repeat through many MVC editing views. This example is the default way we display a checkbox, but similar repetition is found with other input types.
<div class="form-group">
#Html.LabelFor(model => model.IsLive, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8 checkbox">
<div class="col-xs-1">
#Html.EditorFor(model => model.IsLive)
</div>
<div class="col-xs-10">
#Html.CheckboxLabelFor(model => model.IsLive)
</div>
</div>
<a class="infoonclick col-md-1" title="#Html.DisplayNameFor(model => model.IsLive)" data-content="#Html.DescriptionFor(model => model.IsLive)">
<span class="fa fa-info-circle"></span>
</a>
</div>
I am wondering what is the best way to DRY and standardise this?
I want to do something like #Html.DefaultCheckboxEditorFor(model => model.IsLive)
I tried creating a custom HtmlHelper, but this seemed to involve too many hard coded strings to be a good idea.
Rather I feel I should be using EditorTemplates for this, but I can't quite get the syntax right. The model for the view is a bool, but I need to get property specific stuff like the display name and descriptions.
#model bool
<div class="form-group">
#Html.LabelFor(model => model.IsLive, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8 checkbox">
<div class="col-xs-1">
#Html.EditorFor(model => model.IsLive)
</div>
<div class="col-xs-10">
#Html.CheckboxLabelFor(model => model.IsLive)
</div>
</div>
<a class="infoonclick col-md-1" title="#Html.DisplayNameFor(model => model.IsLive)" data-content="#Html.DescriptionFor(model => model.IsLive)">
<span class="fa fa-info-circle"></span>
</a>
</div>
I have a project where most of my views look like:
(This also works with multi-level deep complex objects, but not with any type of collection, like IEnumerable, although it could be modified to do so)
<h3>Edit existing page</h3>
<div class="col-xs-12">
#using (Html.BeginForm("Edit", "Page", FormMethod.Post, new { role = "role" }))
{
#Html.EditorForModel()
<input type="submit" value="Save" class="btn btn-primary" />
}
</div>
I think that's pretty cool. So the model looks like:
public class PageEditViewModel
{
[Editable(false)]
[DisplayName("Page Id")]
public Guid Id { get; set; }
[Editable(false)]
[DisplayName("Url to resource (format: '/my-resource' or '/sub/resource)'")]
public string Url { get; set; }
[Required]
[MaxLength(50, ErrorMessage = "Maximum Length of 50 Exceeded.")]
[DisplayName("Title for page (must match Url ex: 'My Resource' or 'Sub Resource'")]
public string PageTitle { get; set; }
[MaxLength(int.MaxValue, ErrorMessage = "Content Exceeded Maximum Length")]
[DataType(DataType.MultilineText)]
public string Content { get; set; }
}
I have some editor templates:
\Views\Shared\EditorTemplates\multilinetext.cshtml
#model object
#{
var htmlAttributes = this.ViewData.ModelMetadata.GetHtmlAttributes();
}
<div class="form-group #Html.ErrorClassFor(m => m, "has-error")">
#Html.LabelFor(m => m, new { #class = "control-label" })
<div class="controls">
#Html.TextAreaFor(
m => m,
8, 8,
htmlAttributes)
#Html.ValidationMessageFor(m => m, null, new { #class = "help-block" })
</div>
</div>
And it all magically works with the a modified version of object.cshtml:
#model object
#using System.Text;
#using System.Data;
#{
ViewDataDictionary viewData = Html.ViewContext.ViewData;
TemplateInfo templateInfo = viewData.TemplateInfo;
ModelMetadata modelMetadata = viewData.ModelMetadata;
System.Text.StringBuilder builder = new StringBuilder();
string result;
// DDB #224751
if (templateInfo.TemplateDepth > 2)
{
result = modelMetadata.Model == null ? modelMetadata.NullDisplayText
: modelMetadata.SimpleDisplayText;
}
foreach (var prop in modelMetadata.Properties.Where(pm =>
pm.ShowForEdit
//&& pm.ModelType != typeof(System.Data.EntityState)
&& !templateInfo.Visited(pm)
)
.OrderBy(pm => pm.Order))
{
//Type modelType = Model.GetType();
Type modelType = modelMetadata.ModelType;
System.Reflection.PropertyInfo pi = modelType.GetProperty(prop.PropertyName);
System.ComponentModel.DataAnnotations.DisplayAttribute attribute = pi.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.DisplayAttribute;
if (attribute != null
&& !string.IsNullOrWhiteSpace(attribute.GetGroupName()))
{
//builder.Append(string.Format("<div>{0}</div>", attribute.GetGroupName()));
builder.Append(Html.Partial("Partial-GroupName", attribute.GetGroupName()));
}
builder.Append(Html.Editor(prop.PropertyName, prop.TemplateHint ?? prop.DataTypeName).ToHtmlString());
}
result = builder.ToString();
}
#Html.Raw(result)
Example output:
My EditFor templates are versions of MacawNL BootstrapEditorTemplates (which I have no affiliation with).

Field required attribute acidentially invoked but clicking a button

I have these fields, and I implemented required attribute on them.
#using (Html.BeginForm("Edit", "ChannelsGrid", FormMethod.Post, new {name = "channelForm", #class = "channelForm", #enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.HiddenFor(model => Model.Id)
<div class="row">
<div class="col-md-6">
#Html.Label("Part/Location", new {#class = "control-label"})
#Html.TextBox("PartLocation", null, new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Index", new {#class = "control-label"})
#Html.TextBox("Index", null, new {#class = "form-control"})
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.Label("Measurement", new {#class = "control-label"})
#Html.DropDownListFor(model => model.Measurement, (SelectList)ViewBag.Measurements, "-- Select Measurement --", new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Location", new {#class = "control-label"})
#Html.DropDownList("Directions", ViewBag.DirectionTypes as List<SelectListItem>, "-- Select Direction --", new { #class = "form-control", #required = "required" })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.ChannelGroupId, new {#class = "control-label"})
#Html.DropDownListFor(x => x.ChannelGroupId, Model.ChannelGroups, "Select Channel Group", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ChannelGroupId)
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addChannelGroup" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Group</i>
</a>
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addMeasurement" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Measurement</i>
</a>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.Label("Channel name: ", new {id = "channelName", #class = "control-label"})
</div>
<div class="col-md-6">
#Html.TextBox("HiddenTextBox", null, new {#class = "hidden"})
<div class="col-md-1">
#Html.TextBoxFor(a => a.Name, new {#class = "hidden"})
</div>
</div>
</div>
</div>
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<input type="button" value="Cancel" id="channelGroupButton" />
#*<button id="channelGroupButton">Cancel</button>*#
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<input type="button" value="Cancel" id="measurementButton" />
#*<button id="measurementButton">Cancel</button>*#
</div>
</div>
}
I also have two buttons which are used to toggle other textboxes in this form. Here is the code.
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<button id="channelGroupButton">Cancel</button>
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<button id="measurementButton">Cancel</button>
</div>
</div>
The problem is whenever I click these two Cancel buttons in that field, the three fields seems to be invoked and there is brown border around the textbox dropdownlist. I guess these field have been submitted. But I thought I use button element instead of type button of an input so I can eliminate the submitting action of the button, right? Any clues? And how can I click these Cancel buttons withouts invoking validation in these other field?
Edited: I changed all the buttons to input type="button" and the validation of these other field dissapeared. Can someone explain?
This is my viewmodel:
namespace CrashTestScheduler.Entity.ViewModel
{
public class ChannelViewModel
{
public int Id { get; set; }
//[Display(Name = "Name")]
//[Required(ErrorMessage = "Please specify the channel name.")]
public string Name { get; set; }
public string Description { get; set; }
public string ChannelGroupName { get; set; }
public string MeasurementName { get; set; }
[Required(ErrorMessage = "Please select a channel group.")]
public int ChannelGroupId { get; set; }
public IEnumerable<SelectListItem> ChannelGroups { get; set; }
//[Required]
public string Measurement { get; set; }
}
}
The reason your form is submitting when clicking buttons is that the default action for a <button> element is type="submit" (refer documentation). You need to explicitly set the type attribute
<button type="button" ....>
However you have numerous issues with your approach.
By removing the [Required] attributes and using the required =
"required" html attribute, you now need to include manual
validation on the controller (never trust the user!)
Your mixing up Razor and manual html in the view, potentially
creating problems for model binding. Some of your label elements
wont work. (e.g. the first one is associated with a control named
"Part/Location" but there is no control named "Part/Location").
The user interface where your force users to click buttons to swap
between textboxes and dropdown lists is confusing and a sure way to
lose customers. Instead you should use an autocomplete control such
as jQuery Autocomplete which allows selection from a list or
direct text entry.
Your view model should contain validation attributes for its properties and can be simplified to
public class ChannelViewModel
{
public int Id { get; set; }
[Display(Name = "Part/Location")]
[Required]
public string PartLocation { get; set; }
public string Index { get; set; }
[Required]
public string Measurement { get; set; }
[Required]
[Display(Name = "Location")]
public int Direction { get; set; }
.... // other properties
public SelectList DirectionList { get; set; }
}
View
#Html.HiddenFor(model => Model.Id)
#Html.LabelFor(m => m.PartLocation, new {#class = "control-label"})
#Html.TextBoxFor(m => m.PartLocation, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PartLocation)
#Html.LabelFor(m => m.Index, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Index, new {#class = "form-control"})
#Html.LabelFor(m => m.Measurement, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Measurement, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Measurement)
#Html.LabelFor(m => m.Direction, new {#class = "control-label"})
#Html.DropDownListFor(m => m.Direction, Model.DirectionList, "-- Select Direction --", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Direction)
.... // more controls
The attach the autocomplete to $(#Measurement).autocomplete({...
This will give you client and server side validation out of the box, and a better user interface.

MVC Validation to accept DateTime in ddMMyyyy format

I just want to accept Date in ddMMyyyy format while submiting. But its gives an error like
The field FromDate must be a date.
But, When I put date in MMddyyyy it accepts pkkttrfg roperly.
My Model is
public class CompareModel
{
[Required]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime FromDate { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime TODate { get; set; }
}
My View Part is
<div class="form-group">
#Html.LabelFor(model => model.FromDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FromDate)
#Html.ValidationMessageFor(model => model.FromDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TODate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TODate)
#Html.ValidationMessageFor(model => model.TODate)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
The problem is behind the scenes it uses javascript to validate this and you need to overwrite this.
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
});
Which was taken from this answer
Just try adding
<system.web>
<globalization culture="en-GB"/>
</System.web>
Its work for me with same issue
same kind of question i answer before
DatePicker format issue
Try to set the culture in web config that match with date format.
<globalization uiCulture="en" culture="en-AU" />
See this link ASP.NET Date time support for different cultures
http://maheshde.blogspot.com.au/2011/09/aspnet-date-time-support-for-different.html

Resources