Change default asp.net mvc5 validation messages - c#

This is my model's date property:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy.mm.dd}")]
[Required(ErrorMessage = "You need to fill this")]
[DataType(DataType.DateTime, ErrorMessage = "Type proper date")]
[Display(Name = "Weight Date")]
public DateTime? WeightDate { get; set; }
This is how I render bootstrap's datepicker
#Html.EditorFor(x => x.WeightDate, new { htmlAttributes = new { #id="WeightDate" #class = "form-control datepicker", #required = "required" }})
#Html.ValidationMessageFor(m => m.WeightDate, "", new { #class = "text-danger" })
Validation seems to working (I can see "You need to fill this" when entering empty datepicker value). The problem is that I can see other messages, which I would don't want to see (or at least change their messages):
When I enter invalid data, I am getting error (from client side):
The field Weight date must be a date.
When I submit invalid data, I am getting error (from server side):
The value '202441.02.03' is not valid for Weight date.
How can I change those messages?

Related

Unable to update date due to format in MVC

Snippet from Model
[Display(Name = "Updated Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<DateTime> updatedAt { get; set; }
Snippet from Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(NcRecordClass model)
{
if (ModelState.IsValid)
{
var NcRecord = new NcRecordClass()
{
Id = model.Id,
updatedAt = model.updatedAt,
note = model.note
};
db.Entry(NcRecord).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Edit", new { id = model.Id, update = true });
}
return View(model);
}
Snippet from View
#Html.TextBoxFor(model => model.updatedAt, #"{0:dd\/MM\/yyyy}", new { #class = "form-control" })
When I try to update this column using the value '25/11/2020' , this warning will come out
The value '25/11/2020' is not valid for Updated Date.
I want to use the dd/MM/yyyy format in the application.
By the way, I use Postgres DB for this project (Datatype for updatedAt is 'timestamp without time zone'.
I have a similar project using the same code, the only difference is that project is using MSSQL server. And that project have no problem like this.
The [DisplatFormat] attribute is only respected when using DisplayFor() or EditorFor(). To format a value using TextBoxFor(), you need to use an overload that accepts a format string:
#Html.TextBoxFor(m => m.updatedAt,"{0:dd/MM/yyyy}", new { type = "date" , class = "form-control"})
Answer by Sergey partly helped. When I put the type = "date", the textbox become a datepicker which was even better, and I can update the date. But the problem was after I update, the value shown on the textbox was "dd/mm/yyyy" literally. Then I found out that The date of an html input element of type date must be formatted in respect to ISO8601, which is: yyyy-MM-dd Link Here .
So finally, the code that work is this:
#Html.TextBoxFor(model => model.updatedAt, #"{0:yyyy-MM-dd}", new { #class = "form-control", type = "date" })

How to store dd/MM/yyyy Datetime types into Database using ASP.NET MVC?

I am working on a Inventory project but I can't save Datetime datatypes like dd/MM/yyyy into Database. I know Database uses yyyy-MM-dd as standard Datetime but it also accepts MM-dd-yyyy(I think compiler converts it to yyyy-MM-dd).
This is what I have:
Model
[Required(ErrorMessage = "*Ingrese una fecha.")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name ="FECHA")]
public DateTime Fecha { get; set; }
View
#Html.LabelFor(m => m.Entrada.Fecha, new { #class = "control-label" })
#Html.TextBoxFor(m => m.Entrada.Fecha, "{0:dd/MM/yyyy}", new { #class = "form-control datepicker" })
#Html.ValidationMessageFor(m => m.Entrada.InventarioId, "", new { #class = "text-danger" })
When clicking the submit button it doesn't add to database, but when I write any Datetime with mm/dd/yyyy(For example 08/21/2019) type, it submits to database. I can't find solution on the internet.
You can try the following
bool parsed = false;
DateTime outDate;
parsed = DateTime.TryParseExact(inputDate, "dd-MM-
yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None,
out outDate);
if(parsed)
{
usr.DogumTarihi = outDate.ToString("yyyy-MM-dd");
}
else
{
// Invalid date has been passed
}
If you are working with DateTime and not string, the way the database stores displays the date will be yyyy-MM-dd. Sometimes if the date is not sent properly and seeing as your DateTime field is not nullable, it send the value 01/01/0001 (annoying right) so this is what i do...
In the model,
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true, NullDisplayText = "NULL")]
In the view, i have
#Html.TextBoxFor(m => m.Entrada.Fecha, new { #class = "form-control datepicker", placeholder = "Enter Date", id = "Date", autocomplete = "off" })
and in the date picker js options,
$(document).ready(function () {
$('.datepicker').datepicker({
dateFormat: "dd/mm/yy"
});
});
This way, date is stored how database is configured and it is however displayed in the format dd/MM/yyyy. I know it does not answer the question of storing the date in the format you want but this way, you can DISPLAY the date in the format you want, both during submission, editing and displaying it.

MVC5 Pattern regular expression validation is not working in textarea

When I add any regular expression pattern in MVC for textarea it's not working. When I click on submit button the wrong value is added to database
My View Code:
#Html.TextAreaFor(model => model.MyEntity.Item, new { #required = "required", #class = "form-control english_only", #placeholder = "Item", #maxlength = "120", #Pattern = #"[^A-Za-z0-9]" })
My Model Code:
[StringLength(150)]
public string Item{ get; set; }
This is just for any other who have this problem...
Based on Developers comments:
HTML5 <textarea> element does not support pattern attribute
so the solution is by MVC built in validation (with jquery.validate.js) and jquery.validate.unobtrusive.js)
So this problem solve by change my model to be:
[StringLength(150)]
[RegularExpression("^[0-9]*$", ErrorMessage = "UPRN must be numeric")]
public string Item{ get; set; }
and also include the jquery.validate.js in my view or partial view
Ore simply change my html helper to be text box instead of text Area as following:
#Html.EditorFor(model => model.Item, new { htmlAttributes = new { #class = "form-control english_only", #placeholder = "Only english text", #required = "required", #Pattern = #"^[a-zA-Z0-9$#$!%*?&#^-_. +]+$", #title = "please insert english text only", #autocomplete= "off", #maxlength = "120" } })

My date doesn't seem to be posting back in the form to the controller

My model has a object which has a date property...
[Required(ErrorMessage="{0} is required")]
[Display(Name="Donation date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DonationDate { get; set; }
The view has an editor for it....
<div class="editor-label">
#Html.LabelFor(model => model.Donation.DonationDate)
</div>
<div class="editor-field">
#Html.TextBox("txtDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { #class = "date" })
#Html.ValidationMessageFor(model => model.Donation.DonationDate)
</div>
The controller just receives back the model... but when I do this in the controller and give it to another view...
ViewBag.Date = model.Donation.DonationDate;
Every time I just get back
1/1/0001 12:00:00 AM no matter what the date was set to. Any thoughts? Thanks!
Forgot to mention... I'm also using JQuery datepicker on the editor field:
$('.date').attr("placeholder", "dd/mm/yy").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
});
You can use TextBoxFor so that the view engine knows how to label the form field appropriately (so that the model binder will recognize it on postback):
#Html.TextBoxFor(model => model.Donation.DonationDate, new { #class = "date" })
Alternatively, you could name the textbox correctly manually. I'm not sure exactly what that would look like ...
Update
Ok, I as curious so I checked. The naming convention for nested fields uses the dot notation. So you should be able to write this:
#Html.TextBox("Donation.DonationDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { #class = "date" })
Update #2
To format the correctly, apply an attribute to the DonationDate property in your model:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
For this to work, you also have to use #Html.EditorFor instead of TextBoxFor.

String.Format for currency on a TextBoxFor

I am trying to get #String.Format("{0:0.00}",Model.CurrentBalance) into this #Html.TextBoxFor(model => model.CurrentBalance, new { #class = "required numeric", id = "CurrentBalance" })
I just want the currency to show up as .00 inside of my textbox but am having no luck. Any ideas on how I do this?
string.format("{0:c}", Model.CurrentBalance) should give you currency formatting.
OR
#Html.TextBoxFor(model => model.CurrentBalance, new { #class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })
#Html.TextBoxFor(model => model.CurrentBalance, "{0:c}", new { #class = "required numeric", id = "CurrentBalance" })
This lets you set the format and add any extra HTML attributes.
While Dan-o's solution worked, I found an issue with it regarding the use of form-based TempData (see ImportModelStateFromTempData and ExportModelStateToTempData). The solution that worked for me was David Spence's on a related thread.
Specifically:
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public decimal? Price { get; set; }
Now if you use EditorFor in your view the format specified in the annotation should be applied and your value should be comma separated:
<%= Html.EditorFor(model => model.Price) %>

Categories

Resources