I am using an EditorTemplate for a DateTimeOffset field that consists of...
#model DateTimeOffset?
#Html.TextBox("", String.Format("{0:u}", Model.HasValue ? Model : DateTimeOffset.UtcNow), new { #class = "datepicker" })
This works in 90% of my forms, I get values like 2012-07-31 11:30:09Z. However, I have one form that will not apply any formatting. The HTML output of the working input field and the non-working input field are the same.
Working...
<input class="datepicker hasDatepicker" data-val="true" data-val-required="'Launch Time' must not be empty." id="LaunchTime" name="LaunchTime" type="text" value="2012-07-31 11:30:09Z">
Non-working...
<input class="datepicker hasDatepicker" data-val="true" data-val-required="'Launch Time' must not be empty." id="LaunchTime" name="LaunchTime" type="text" value="07/31/2012 11:30:09 +00:00">
The only thing that I have found that fixes the problem is to change the TextBox name field...
#Html.TextBox("asdf", String.Format("{0:u}", Model.HasValue ? Model : DateTimeOffset.UtcNow), new { #class = "datepicker" })
However, this then changes my input field to...
<input class="datepicker hasDatepicker" id="LaunchTime_asdf" name="LaunchTime.asdf" type="text" value="2012-07-31 11:30:09Z">
which will then break the form submission, and removes the validation rules.
The model...
[DisplayFormat(DataFormatString = "{0:u}" , ApplyFormatInEditMode = true)]
public DateTimeOffset LaunchTime { get; set; }
The problem is that the only format that seems to work for the datetime value is yyyy-mm-dd. /s do not work.
Related
I use a partial view of a create form in multiple page on my calendar system. On my home page everything is working properly without requiring anything. But on my other page, it need a model to be passed to it
#await Html.PartialAsync("Create.cshtml", new Horraire {
Jour = jourID,
Semaine = semaine.GetValueOrDefault(),
début = new DateTime(),
fin = new DateTime()
});
The problem is, I have no idea on how to give it an empty datetime that doesn't break the input by adding milliseconds that the model doesn't accept
I tried to pass it a null datetime, but it's not accepted by the model due to the datetime being non nullable and required
Working form
<input class="form-control" type="time" data-val="true" data-val-required="The Heure de Fin field is required." id="fin" name="fin" value="">
Problematic generated form
<input class="form-control" type="time" data-val="true" data-val-required="The Heure de Fin field is required." id="fin" name="fin" value="00:00:00.000">
I would like the form to work just like the other, and the value to truely be empty. This form need to be completed a lot of time and should be filled as fast as possible
Your DateTime property needs to be nullable, even if it's required, i.e.:
public class Horraire
{
...
[Required]
public DateTime? fin { get; set; }
}
Then, the value will initially be blank on the form, but if the user fails to pick a date and time, then you'll still get a validation error.
You can use a Nullable datetime which is specifically for null datetime purpose.
DateTime? nullableDateTime = null;
I have a very different kind of problem.
I have deployed my mvc application to live server.
It has date time format like this '01/07/2019'.
I have a textbox which is populated from jquery datetimepicker. It populates like this 27/Jul/2019 but in sql table it stores like 2019-07-17 00:00:00.000
and after binding the data from database to textboxfor, it appears like this 27-07-2019.
And upon saving it throws error for all the dates that are greater than 12 as a day e.g. 13/07/2019 but for 13/Jul/2019 it works good.
how to tackle this?
#Html.EditorFor(model => model.InspectionReport.InspectionDate, new { htmlAttributes = new { #class = "form-control input-sm pull-right text-box single-line" } })
jquery:
$("#InspectionReport_InspectionDate").datepicker({ dateFormat: 'dd/M/yy' });
class:
[Required]
[Display(Name = "Inspection Date")]
[DisplayFormat(DataFormatString = "{0: dd-MMM-yyyy}")]
public DateTime InspectionDate { get; set; }
In a date field of data type DateTime(2), a date value is stored as a value with no format.
Thus, to display the value, apply the format you wish, or a default format will be applied.
Try this,
#Html.TextBoxFor(model => model.InspectionReport.InspectionDate, "{0:dd-MMM-yyyy}", htmlAttributes: new { #type="date" })
I have a textbox for date of birth on the index page. I have to validate user to enter complete date format(mm/dd/yyyy), but its allowing to post 03/12(mm/dd) without year and in c# side it converted to 03/12/2015.
My requirement is to validate user to enter complete date format.
I used data annotation but that also not handling (mm/dd) as invalid date.
#Html.TextBoxFor(m => m.Search.DOB, new { #class = "form-control datepicker" })
Maybe you could use regular expression in javascript,
when fucusout event be triggered!
or solve the problem by following
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime StartDate { get; set; }
You can use the html5 form validation it works without javascript.
For example:
<input type="text"
name="DOB"
placeholder="MM/dd/yyyy"
title="MM/dd/yyyy"
required
pattern="^([1-9]|1[0-2])/([1-9]|1[0-9]|2[0-9]|3[0-1])/\d{4}$" />
I'm having difficulty writing a custom remote validator that will evaluate distinct pairs of fields from a list? The list has 2 fields that need to be validated: Description and Amount. This is my list.
#for (int i = 0; i < Model.MyList.Count(); i++)
{
#Html.TextBoxFor(m => m.MyList[i].Description)
#Html.TextBoxFor(m => m.MyList[i].Amount)
#Html.ValidationMessageFor(m => m.MyList[i].Description)
#Html.ValidationMessageFor(m => m.MyList[i].Amount)
}
The validation rules are as follows:
Amount must be zero or greater. It cannot be blank.
Description is required only when an amount is greater than zero.
When description is entered, the amount must be greater than zero.
I've seen (and implemented) solutions like these, but they don't address this type of scenario of evaluating multiple distinct pairs of fields that are in a list.
Multiple fields validation using Remote Validation
how to use multiple AdditionalFields in remote validation - asp.net mvc
This is in my model. And the validation rules for Amount work. But the custom remote validator (ValidateDescriptionAmountPair) for Description fails.
[Range(0, int.MaxValue, ErrorMessage = "Amount must be 0 or greater.")]
[Required(ErrorMessage = "Amount is required.", AllowEmptyStrings = false)]
public decimal Amount { get; set; }
[Remote("ValidateDescriptionAmountPair", "MyController", AdditionalFields = "Amount")]
public string Description { get; set; }
This is my custom validator.
[HttpGet]
public virtual JsonResult ValidateDescriptionAmountPair(string Description, string Amount)
{
bool isOkay = true;
string reasonItsInvalid = string.Empty;
// TODO: Add code to evaluate business rules, and change
// isOkay and reasonItsInvalid accordingly.
if (isOkay)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(reasonItsInvalid, JsonRequestBehavior.AllowGet);
}
}
I put a breakpoint in ValidateDescriptionAmountPair. This method gets called, but the Description and Amount values arrive as NULL rather than with expected values.
These are some markup examples for fields rendered in the view.
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_0__Description" name="MyList[0].Description" type="text" value="Paid for this" aria-invalid="false">
<input class="form-control text-right" value="5000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_0__Amount" name="MyList[0].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_0__Amount-error">
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_1__Description" name="MyList[1].Description" type="text" value="test" aria-invalid="false" aria-describedby="MyList_1__Description-error">
<input class="form-control text-right" value="10000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_1__Amount" name="MyList[1].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_1__Amount-error">
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_2__Description" name="MyList[2].Description" type="text" value="Paid for that" aria-invalid="false">
<input class="form-control text-right" value="20000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_2__Amount" name="MyList[2].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_2__Amount-error">
What I think may be happening is that the names applied to list entries don't exactly match the "Description" and "Amount" parameter names in ValidateDescriptionAmountPair(), because they have indexes applied to the names. In other words, the field names are MyList[1].Description and MyList[1].Amount, but the ValidateDescriptionAmountPair() method is looking for Description and Amount. That's just a hunch which could be totally off base. If indeed that's why it fails, then what is the solution?
At any rate, I need to be able to implement the business rules noted above, and I would prefer to do this using an MVC data annotation or custom remote validation approach rather than hand-rolling some client-side jQuery to do this. Thanks for your help.
I could not achieve this in remote validation. But you achieve this using controller and #Html.ValidationSummary()
Add #Html.ValidationSummary() in view
#Html.ValidationSummary();
#for (int i = 0; i < Model.MyList.Count(); i++)
{
#Html.TextBoxFor(m => m.MyList[i].Description)
#Html.TextBoxFor(m => m.MyList[i].Amount)
#Html.ValidationMessageFor(m => m.MyList[i].Description)
#Html.ValidationMessageFor(m => m.MyList[i].Amount)
}
In Controller check the logic for distinct value and add the error message to the summary
[HttpPost]
public ActionResult MultipleValidation(List<MyList> model)
{
bool isOkay = true;
string reasonItsInvalid = string.Empty;
// TODO: Add code to evaluate business rules, and change
// isOkay and reasonItsInvalid accordingly.
if (!isOkay)
{
// Message to display in validation summary
ModelState.AddModelError("", "Duplicate Record");
}
return View("View", model);
}
I have a view built on Bootstrap 3 and ASP.NET MVC 5 for editing user profile information, but it displays in the incorrect format on the form.
The database is Neo4j and I'm using Neo4jClient to interact with the database from .NET. Neo4jClient requires the use of DateTimeOffset objects instead of DateTime objects to use Json.NET's serializer for passing to Neo4j's REST interface. Therefore, my model uses a DateTimeOffset object to store the birthday for a user.
Here is my form field in my view:
<div class="form-group">
<label class="col-md-4 control-label" for="Birthday">Birthday</label>
<div class="col-md-4">
#Html.TextBoxFor(model => model.Birthday, new { #class = "form-control input-md datepicker", placeholder = "Birthday" })
<span class="help-block">Please enter your birthday</span>
</div>
</div>
The date has the following format when printed to the form:
M/dd/yyyy hh:mm:ss t -zzz
However, it should have this format since we just need the date part:
MM/dd/yyyy
I have tried using the DataFormatString annotation on the model property, but it still doesn't display in the correct format:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTimeOffset Birthday { get; set; }
Does this annotation still apply for DateTimeOffset objects? How do I fix the string formatting?
Answered here: https://stackoverflow.com/a/6140014/211747
Summary: TextBoxFor doesn't respect DataFormatString, you need to use EditorFor, but that doesn't support custom HTML attributes, so you need an editor template (Views\Shared\EditorTemplates\DateTimeOffset.cshtml).