RangeAttribute Data Annotation Not Working as Expected - c#

I am developing an ASP.NET MVC2 application in which I have a User class with a property named SecurityQuestionID as follows:
public class User
{
[RangeAttribute(1, 5, ErrorMessage = "Security Question is required")]
[DisplayName("Security Question")]
public virtual int SecurityQuestionID { get; set; }
}
The SecurityQuestionID field gets populated from a dropdown in the view as follows:
<%: Html.LabelFor(model => model.SecurityQuestionID)%>
<%: Html.DropDownListFor(model => model.SecurityQuestionID, ViewData["securityQuestions"] as SelectList,"Choose a Question",null) %>
<%: Html.ValidationMessageFor(model => model.SecurityQuestionID)%>
The controller sends the security questions to the view by using view data as follows:
ViewData["securityQuestions"] = new SelectList(_securityQuestionService.GetAll(), "SecurityQuestionID", "Question");
If I don't select a question from the dropdown and hit the submit button, then "The Security Question field is required." message is displayed instead of "Security Question is required". Can anyone help me understand what I am doing wrong here?

If the integer is not nullable, then it is required by default. So the range validation isn't failing but Required validation is failing.
You may want to specify a separate error message for when it is required by adding a required attribute.
[Required(ErrorMessage="Security Question is required")]

It's probably throwing that error because it is a required field. See http://forums.asp.net/p/1391688/2977493.aspx. This is consistent with the fact that the field in question is defined as an int, and not an int?, so it cannot assume a null value.
In other words, it's not hitting your range validator.

Related

With ASP.NET, how do I make display names of properties show in lower case in validation error messages?

In ASP.NET, what is the best way to display field/property names in form validation error messages in lower case?
For example, if I have a Price property on a model, and Price is not nullable, and I leave the Price field blank when filling out a form for this model, then I will get this error message on the form:
The Price field is required.
"Price" is capitalised. Is there any easy way to make it lower case, like the following?
The price field is required.
There must be a way of making these property names show in lower case for every error message. Because yes, if I just wanted it for one property, then I could set a custom error message using the Required attribute:
[Required(ErrorMessage = "The price field is required.")]
public decimal Price { get; set; }
But I'm wondering if there is a way to make these property names show in lower case by default for every error message?
I did find this question with some answers, but the solutions seem pretty complex, and also that person is talking about JSON serialisation, which is a bit different to my case.
Thanks if anyone can share any info on this problem.
If you use ValidationMessageFor on the page like this
#Html.ValidationMessageFor(m => m.Price)
It will show the error message in a span with the class field-validation-error.
So if you now the class you can use css to transform the text to lowercase.
<style>
.field-validation-error {
text-transform: lowercase;
}
</style>
You can try this:
<style>
.field-validation-error {
text-transform: lowercase;
}
.field-validation-error:first-letter {
text-transform: uppercase;
}
</style>

MVC 5 How to Validate Nullable Integers

This has been asked and answered numerous times, but I have a special situation where I have nullable integers in my model.
Model:
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer number")]
public int? Jan { get; set; }
In my edit form, if enter "x", then the browser default error pop-up with "Please enter a number" appears. My own client-side validation doesn't appear to be kicking in. If I enter nothing, then it blows up server-side because a parameter was expected in my repository code.
I need it to validate non-integers on the client and I also need it to handle nulls, when someone tries to submit the form with an empty value. I cannot resort to a Required data annotation, because if I do, no data will be loaded. This is a conversion from legacy code to MVC.
UPDATE - CLARIFICATION:
I'm dealing with a lot of nullable ints. The decision to try and make them required was mine - am open to alternative options. I cannot change the int? in the model for various reasons. So, I need to validate against nulls on the client and server to ensure that integers are entered.
You can use the HTML5 required attribute client side to prevent empty values from being entered. If you really want to ensure no empty values are sent to the server, I believe you are going to need to do some server side validation as well.
HTML5 Required Attribute

How to pre-populate a 'date' input field with Razor/C# values

I have a 'date' type input, and I'm trying to get the Razor code to pre-fill the date with information that the server already has, because it's for an Edit field on an MVC ASP.NET Core app I'm working on.
The code I'm using is:
<input type="date" name="DeliveredDate" id="DeliveredDate" value='#Model["order"].DeliveredDate.ToString("mm/dd/yyyy")'>
I can get the code to show the string in any other part of the page, but is there a trick to getting that same string to populate the value of a date field? All my googling hasn't turned up anything particularly helpful.
You can use either #Html.TextBox() or strongly-typed #Html.TextBoxFor() helper to do so, by either setting DisplayFormatAttribute or date format directly in the helper:
Viewmodel property
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DeliveredDate { get; set; }
View
#Html.TextBox("DeliveredDate", Model["order"].DeliveredDate, "{0:MM/dd/yyyy}", new { type = "date" })
#Html.TextBoxFor(model => model.DeliveredDate, "{0:MM/dd/yyyy}", new { type = "date" })
Or using EditorFor by setting date format, which automatically appends type = "date" attribute:
#Html.EditorFor(model => model.DeliveredDate)
If you're using tag helper, just set asp-for attribute:
<input asp-for="DeliveredDate" type="date" />
Notes:
1) Make sure that you're already set the date value inside controller action, e.g. model.DeliveredDate = DateTime.Now (model has type of Model["order"]).
2) The latter approach requires setting DisplayFormatAttribute in viewmodel property because there's no string formatting parameter to set the format from EditorFor or tag helper itself.
The correct command ended up being
#Model["order"].DeliveredDate.ToString("yyyy-MM-dd")
but then I learned from my instructor that there's a date range that is able to be displayed, and it varies with different platforms, but I'm pretty sure the range that can be displayed is between the years 1950, and 2049.
Once I actually set the dates it was supposed to display to one that was within that range, it worked, and if I tried to display a date outside of that range, it would break again.

Is it possible to Display validation errors when page loads in MVC - 4 (with model validations)

Is it possible to trigger validation error message on page load based on model validations for example.
[Display(Name = "Quantity")]
[Required(ErrorMessage = "Please enter Quantity")]
[Range(1, 1000, ErrorMessage = "Please enter Qty between the range of 1 to 1000")]
[RegularExpression("^([0-9])*$", ErrorMessage = "Please enter valid Qty")]
public int? QTY { get; set; }
If saved value for Qty is 0(zero) in database and I want to fetch it & display on screen which is invalid as per model validation.
So is it possible to trigger that message without any value checks in controller.
Information given is bit scarce but I'll try.
If you're using jQuery Validate on your client, and you which to show error error messages of the said library. you can try to use something like:
$("#myform").validate();
If however you which to show the automatic ajax error message block. I recommend going with what Stephen Muecke proposed in comment.
If you wish for more specific response try to specify all the tools and libraries you have in use regarding validation. Or even simply showing your display solution for form would give ques to what libraries and tools you use.
PS. Try studying the client side solution on showing the wanted error message. If you learn what triggers the message. You should be be able to trigger the same event at ease using an script language etc.
Hope this helps :)

MVC2 client/server validation of DateTime/Date using DataAnnotations

The following are true:
One of my columns (BirthDate) is of type Date in SQL Server.
This very same column (BirthDate) is of type DateTime when EF generates the model.
I am using JQuery UI Datepicker on the client side to be able to select the BirthDate.
I have the following validation logic in my buddy class:
[Required(ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Required")]
[RegularExpression(#"\b(0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2}\b", ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Invalid")]
public virtual DateTime? BirthDate
{
get;
set;
}
There are two issues with this:
This will not pass server side validation (if I enable client side validation it works just fine). I am assuming that this is because the regular expression doesn't take into account hours, minutes, seconds as the value in the text box has already been cast as a DateTime on the server by the time validation occurs.
If data already exists in the database and is read into the model and displayed on the page the BirthDate field shows hours, minutes, seconds in my text box (which I don't want). I can always use ToShortDateString() but I am wondering if there is some cleaner approach that I might be missing.
Thanks
1: This is easily solved by changing DateTime to be non-nullable, meaning the datetime value entered must be parse-able and therefore valid, and then use the:
[DataType(DataType.Date)]
attribute instead of the regular expression. This will make sure the field is required and must be parse-able.
2: This is a templating issue. The easy way is to create a custom Date.ascx template inside of /Views/Shared/EditorTemplates that calls ToShortDateString() and will hook up your jquery datepicker.
This is what mine looks like:
<%# Import Namespace="System.Web.Mvc.Html" %>
<%
string displayText = string.Empty;
if (Model != null)
{
if (DateTime.Parse(Model.ToString()) != DateTime.MinValue)
displayText = DateTime.Parse(Model.ToString()).ToShortDateString();
}
%>
<%= Html.TextBox("", displayText, new { #class = "date-box" })%>

Categories

Resources