I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });
Related
I'm creating a website with ASP.NET MVC5 and I'm using MaterializeCSS for the first time, which looks like a very exciting framework.
However, the checkboxes generated by CheckBoxFor helper become hidden !
When I write :
#Html.CheckBoxFor(m => m.IsAgreeTerms)
The generated HTML is :
<input name="IsAgreeTerms" type="hidden" value="false">
Why does Materialize change my type=checkbox into type=hidden ?
I tried to add type="checkbox" in the CheckboxFor helper, but it doesnt change anything. The only way is to modify in in my browser's console.
The only solution I found is this SO thread.
However, the accepted answer doesn't change anything for me.
The other answer works, but I think it's ugly to add some JS script to modify what Materialize modifies without my consent.
Is there any way to say "Hey, I ask for a type=checkbox, so just let my type=checkbox in the generated HTML" ?
Thank you
UPDATE :
My full ASP.NET MVC code is :
#Html.CheckBoxFor(m => m.IsAgreeTerms, new { #type = "checkbox" })
#Html.LabelFor(m => m.IsAgreeTerms, new { #class = "login-label" })
The full generated HTML is
<input data-val="true" data-val-required="Le champ IsAgreeTerms est requis." id="IsAgreeTerms" name="IsAgreeTerms" type="checkbox" value="true"
<input name="IsAgreeTerms" type="hidden" value="false">
<label class="login-label" for="IsAgreeTerms">IsAgreeTerms</label>
Here's a solution in the form of a html helper. It constructs a checkbox and label in the correct order:
public static IHtmlString CheckBoxWithLabelFor<TModel>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, bool>> expression,
string labelText,
object htmlAttributes = null
)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
var checkBoxWithHidden = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToHtmlString().Trim();
var pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1, StringComparison.Ordinal));
var labelHtml = htmlHelper.LabelFor(expression, labelText).ToHtmlString().Trim();
var result = pureCheckBox + Environment.NewLine + labelHtml + Environment.NewLine + $"<input type=\"hidden\" name=\"{ExpressionHelper.GetExpressionText(expression)}\" value=\"false\" />";
return new MvcHtmlString(result);
}
Is there other html generated by materialize.css? I think this happens because it is not possible apply a custom CSS to element input of type checkbox.
So, the checkbox becomes hidden and other html component represents visually the checkbox. Many components work like that.
UPDATE:
Why is Html checkbox generating an additional hidden input
OP here. Problem looks like more complex.
Actually, when using #Html.CheckBoxFor, MVC5 generates 3 fields, in that order :
Your input, with type="checkbox", binded to your model property
An hidden field (see the Claudio's link for an explaination)
Your label, generated by #Html.LabelFor
Problem is Materialize expects that in another order to work.
In your browser's console, just move the <label> element between the input and the hidden field, and everything works fine !
I found this very useful link, where, basically, it is said that the order of the generated fields by #Html.checkBoxFor will change ... In MVC6 !
As I'm working with MVC5, I use this very ugly solution in my _Layout:
$(":checkbox").each(function () {
$(this).nextAll("label").before($(this))
})
If anyone has a better idea, please feel free to post an elegant solution.
I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });
I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });
I have a text input that uses custom date and time picker script.
<div class="input-group date datetime" data-start-view="4" data-date-format="dd MM yyyy" data-min-view="2" data-link-field="dtp_input1">
<input name="dateOfBirth" class="form-control" size="16" type="text" value="${userInstance?.dateOfBirth}"/>
<span class="input-group-addon btn btn-primary"><span class="glyphicon glyphicon-th"></span></span>
</div>
It gives me this error
Property org.springframework.context.support.DefaultMessageSourceResolvable: codes [rms.User.dateOfBirth,dateOfBirth]; arguments []; default message [dateOfBirth] must be a valid Date
I dont how to solve this. Using the grails dateTime picker tag seems to work but its ugly
The only way is to use SimpleDateFormat. I often use it for forms with a JS-calendar inside:
class YourController {
static SimpleDateFormat sdf = new SimpleDateFormat( 'dd.MM.yyyy' )
def index(){
Date dateOfBirth
try{
if( params.dateOfBirth ) dateOfBirth = sdf.parse( params.dateOfBirth )
}catch( Exception ignoreMe ){}
// do something useful
}
UPDATE:
You must use the propper date format of course. The one I gave in my example dd.MM.yyyy corresponds to 08.02.2014. For strings like February 08 2014 you are gonna need something like MMM dd yyyy.
See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for further info
I've been searching a lot on how to this
There is a lot of posts here and there on how to do it
However I cannot find a way to do what I want
I have this textbox in a TemplateField: (I cannot use a BoundField)
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("myDate", "{0:d/M/yyyy}") %>'>
That works good, but in my website i can change back and forth from english (us) to spanish (mx) so the date format is different and has to change as well.
en-US: M/d/yyyy es-MX: d/M/yyyy
how can i change that format in a postback?
I tried to have the TEXT intruction in a meta:ResourceKey but it displays '<%# Bind("myDate", "{0:d/M/yyyy}") %>' instead of the date
I also tried changing it from codebehind using: Text='<%# GetDate(Container.DataItem) %>'
public string GetDate(object dataItem)
{
DateTime dt;
DataRowView _row = (DataRowView)dataItem;
string fecha = _row["myDate"].ToString();
if (culture == "es-MX")
dt = DateTime.ParseExact(fecha, #"d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
else if(culture == "en-US")
dt = DateTime.ParseExact(fecha, #"M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);
return dt.ToShortDateString();
}
It does the trick but when I try to update or insert I get a null value error :/
Im using visual studio 2012 .net 4.5 and c#
Thanks for your help
rubenc
Well it turned out that this is a way of doing it
The null error was from another value :)
Thanks anyway