I am trying the following RegEx to validate the decimal value like
[RegularExpression("^(?:\\d{1,100000000}(?:\\.\\d{0,6})?)?$")]
[Range(double.MinValue,double.MaxValue)]
public decimal Amount { get; set; }
rendering in the view like
<div class="editor-field">
<%:Html.TextBoxFor(x=>x.Amount)%>
<%:Html.ValidationMessageFor(x=>x.Amount) %>
</div>
the problem is it puts a 0 in the textbox by default, please guide me find out the problem, also if there is a better way to validate the decimal field please do mention...
Try settings the type of your Amount property to nullable:
public decimal? Amount { get; set; }
Related
Need help adding validation on textbox field where the datatype of textbox is decimal and it can have max length of 15 digits or max length of 15 with 4 decimal places.
Example:
1234
123456789012345
123456789012345.1234
This is how part of the code looks like:
public decimal ShipmentWeight { get; set; }
Razor:
#Html.TextBoxFor(model => model.ShipmentWeight, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ShipmentWeight)
Does anyone know how i can achieve this?
Thanks.
I'd like to create template for string, that will include label, textbox with watermark and validation message for registration form.
In addition, I'd like to add notice (eg. star), that the field is required by getting it from model.
So far I have created file string.cshtml in ~/Views/Account/EditorTemplates containing this:
<span class="editor-label>#Html.Label(ViewData.ModelMetadata.Watermark)</span>
<span class="editor-field">#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = ViewData.ModelMetadata.Watermark })</span>
<span class="error_message">#Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>
Model looks like this:
[Required]
[DataType(DataType.Text)]
[Display(Prompt = "First name")]
public string FirstName { get; set; }
And in view I call it as follows:
#Html.EditorFor(m => m.FirstName)
Does anyone have any idea, where do I go wrong?
Your editor template must be called Text.cshtml and not String.cshtml because you use the [DataType(DataType.Text)] attribute.
You could also specify a custom name for the editor template using the UIHint attribute:
[Required]
[DataType(DataType.Text)]
[Display(Prompt = "First name")]
[UIHint("Foo")]
public string FirstName { get; set; }
and now you could have ~/Views/Account/EditorTemplates/Foo.cshtml.
Andree,
Your problem for not showing the message is this line:
<span class="error_message">#Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>
If you look at your rendered HTML source, you see something like the following:
<span class="field-validation-error" data-valmsg-for="<className>.FirstName" data-valmsg-replace="true"></span>
Notice, that it's including the class in the data attribute. However, ubobtrusive doesn't match this. What you need rendered is simply:
<span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
In order to accomplish this, change your code in your editor to:
#Html.ValidationMessageFor(v => v)
Likewise, to make you code easier to read, both of these also work for your other code...
#Html.LabelFor(v => v)
#Html.TextBoxFor(v => v, new { placeholder = ViewData.ModelMetadata.Watermark })
i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?
The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }
Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?
1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl
I have the following properties in my Model
[Required]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber
{
get;
set;
}
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
public string EmailAddress
{
get;
set;
}
The corresponding View is
<td>
Email
</td>
<td>
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress, "*")
</td>
</tr>
<tr>
<td>
Phone #
</td>
<td>
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber, "*")
</td>
When I render this page I see the Required attribute getting triggered. But the DataType attribute is not getting fired if I key in Invalid data.I see the source html and don't see any code being emitted for these validations.
I have the following as a part of my view too
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"/>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"/>
You could consider using ASP.NET MVC 3 Futures. Here is a nice article describing validations there:
public class UserInformation
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[Url]
public string Website { get; set; }
[Required]
[CreditCard]
public string CreditCard { get; set; }
[Required]
[FileExtensions(Extensions = "jpg,jpeg")]
public string Image { get; set; }
}
See this post:
Is the DataTypeAttribute validation working in MVC2?
It's important to note that the DataType Attribute is usually used for formatting purposes, not for validation. Technically there are a wide range of email formats and phone number formats (see here for email: http://www.regular-expressions.info/email.html).
Also, custom converters can be made to convert seemingly non-email strings into emails (me at domain dot com = me#domain.com), and thus having default validation regexs flies out the window. It is left up to the developer to use the correct regex for their specific purpose, and to ensure they only accept address they believe are accurate.
Related to this question, there are some third party data validation annotations for download at http://dataannotationsextensions.org/
I just had a similar issue myself. I had the model setup with a data type of email but it was not being validated as an email. I noticed in the html that the view produced the textbox for the email address had a type of text. I then altered my view as below and this fixed it:
#Html.TextBoxFor(m => m.Email, new { type = "email" })
the was using the jquery validate javascript libary
today I got confused when doing a couple of <%=Html.LabelFor(m=>m.MyProperty)%> in ASP.NET MVC 2 and using the [DisplayName("Show this instead of MyProperty")] attribute from System.ComponentModel.
As it turned out, when I put the attribute on an overridden property, LabelFor didn't seem to notice it.
However, the [Required] attribute works fine on the overridden property, and the generated errormessage actually uses the DisplayNameAttribute.
This is some trivial examplecode, the more realistic scenario is that I have a databasemodel separate from the viewmodel, but for convenience, I'd like to inherit from the databasemodel, add View-only properties and decorating the viewmodel with the attributes for the UI.
public class POCOWithoutDataAnnotations
{
public virtual string PleaseOverrideMe { get; set; }
}
public class EditModel : POCOWithoutDataAnnotations
{
[Required]
[DisplayName("This should be as label for please override me!")]
public override string PleaseOverrideMe
{
get { return base.PleaseOverrideMe; }
set { base.PleaseOverrideMe = value; }
}
[Required]
[DisplayName("This property exists only in EditModel")]
public string NonOverriddenProp { get; set; }
}
The strongly typed ViewPage<EditModel> contains:
<div class="editor-label">
<%= Html.LabelFor(model => model.PleaseOverrideMe) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.PleaseOverrideMe) %>
<%= Html.ValidationMessageFor(model => model.PleaseOverrideMe) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.NonOverriddenProp) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.NonOverriddenProp) %>
<%= Html.ValidationMessageFor(model => model.NonOverriddenProp) %>
</div>
The labels are then displayed as "PleaseOverrideMe" (not using the DisplayNameAttribute) and "This property exists only in EditModel" (using the DisplayNameAttribute) when viewing the page.
If I post with empty values, triggering the validation with this ActionMethod:
[HttpPost]
public ActionResult Edit(EditModel model)
{
if (!ModelState.IsValid)
return View(model);
return View("Thanks");
}
the <%= Html.ValidationMessageFor(model => model.PleaseOverrideMe) %> actually uses [DisplayName("This should be as label for please override me!")] attribute, and produces the default errortext "The This should be as label for please override me! field is required."
Would some friendly soul shed some light on this?
Model binding and metadata using the strongly-typed helpers looks at the declared, rather than the runtime, type of the model. I consider this a bug, but apparently the MVC team disagrees with me, as my Connect issue on this was closed as "By Design."
I ran into this problem using [DisplayName("Profile Name")] and instead used [Display(Name = "Profile Name")] which fixed the problem in my case. I'm not sure if this would be useful.
The former is from System.ComponentModel whilst the latter is from System.ComponentModel.DataAnnotations.
I had the same issue when I had a partial view strongly-typed to an interface. The interface defined a DisplayName and the class that implemented the interface tried to override it. The only way I found to get it to respect the override was to type to the implementing class. I had to either change the view's model type or cast. Unfortunately, that completely negates the benefits of using the interface as the model type. I am guessing that I will end up with some level of duplicated view markup for each implementing class while not casting within the strongly-typed "helpers".
In the remote chance that this type of workaround is even remotely helpful (not getting my hopes up), here is an example. There are certainly ways of working handling into this for all possible implementing classes that try to override a name, but it is definitely more hassle than it should be.
public interface IAddressModel {
...
[DisplayName("Province")]
public string Province { get; set; }
...
}
public class UsAddressModel : IAddressModel {
...
[DisplayName("State")]
public string Province { get; set; }
...
}
<%= Html.LabelFor(m => m.State) %> <!--"Province"-->
<%= Html.LabelFor(m => (m as UsAddressModel).State) %> <!--"State"-->
Ok, I seem to have found a workaround if you don't use the Required tag with it! just use a regular expression or length attribute to determine if there is a valid entry. Hope this helps, though it's a little late.
[RegularExpression(#"^[1-9][0-9][0-9]$")] //validates that there is at least 1 in the quantity and no more than 999
[DisplayName("Quantity:")]
public string quantity { get; set; }
Still works.
In my case I was forgotten to make it a property by using getters and setters.
Instead of
public string CompanyName;
I should have used
public string CompanyName {get;set;}