Can I restrict user to enter only numbers using DataAnnotations?
Below is the property which I have in my Model
[Display(Name = "Fiscal Year")]
[Required(ErrorMessage = "Fiscal Year is required")]
public int FiscalYear { get; set; }
Below is the definition which I am using in .chtml (razor view):
#Html.TextBoxFor(model => model.project.FiscalYear)
I want to allow users only to enter numbers. Any suggestions?
Thanks,
Balaji
Get the Nuget package called DataAnnotationsExtensions.. then use it like below:
[Integer(ErrorMessage="This is needs to be integer")]
public int CustomerId { get; set; }
It will put the proper the validation in place assuming that you have jQuery validation plugin and unobtrusive validation enabled.
You can use RegularExpression attribute
Related
define both include and exclude and also example.
why we use include and exclude in MVc. where we use
We use include and exclude in model binding. These features provide more control and security in the binding process for us. Let me explain with one example.
We have a model like this:
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Address { get; set; }
public DateTime AddedDate { get; set; }
}
By default MVC bind all of these fields from your view to your controller. But we don't want to bind AddedDate, because we want to add data to this field in the controller. So with excluding feature, we can tell the MVC that don't bind automatically AddedDate.
public ActionResult Edit([Bind(Exclude = "AddedDate")] TestModel model)
Or in the other situation think that your boss told you that you shouldn't let the users change their Address in the edit form. One way is that you change your view and add a hidden field inside of view to keep the Address value for binding. but sometimes due to the security issues, you cannot use this approach with sensitive data like Id, password... So you can simply exclude that fields from binding.
public ActionResult Edit([Bind(Exclude = "Address")] TestModel model)
In the same way, Include will tell MVC which fields should be part of the binding.
I will highly recommend you to use ViewModel when you can, instead of using Include and Exclude features.
I read a lot of topics which mention that the primary purpose for DataType is displaying data and not validating data. So I tried the following for testing
public partial class test
{
public int Id { get; set; }
[DataType(DataType.EmailAddress)]
public string email { get; set; }
[DataType(DataType.Date)]
public System.DateTime date { get; set; }
}
And I have noted that both the date & email will have validation checking,For example I can not write invalid email address or invalid date format ?
So my question is why a lot of topics mention that the primary purpose for DataType is used for formatting the properties and not for validating them. While in my test I found that specifying DataType for the property such as email & Date will create validation login also?
Can anyone advice?
Thanks
I have properties declared in my view model like:
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime DateStart { get; set; }
However, I am still getting a default The Start field is required error message. I assume this is because a non-nullable DateTime is implicitly required, and the Required attribute is ignored. Is there a way to customise my error message for these specific properties, besides making them nullable?
You right, your problem is that your property is not nullable. For not nullable properties attribute Required is meaningless. When there is no StartDate value, validation is not go to your Required attribute and fails on previous step. If you want to get your ErrorMessage you should
use:
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime? DateStart { get; set; }
You cannot customize ErrorMessage for nonullable types that get null on modelbinding, cause it is hardcoded deep in MVC framework.
I've started with refresh new test project in MVC 4 and create a test model
public class TestModel {
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime DateStart { get; set; }
}
Then in my model I just have this:
#using(Html.BeginForm()){
#Html.ValidationMessageFor(a => a.DateStart);
#Html.TextBoxFor(a => a.DateStart)
<input type="submit" value="add"/>
}
When I remove clean the text box and hit submit, I am getting the customized error message instead of the default.
The Date field is required for Start.
This make sense to me, imagine if this is a multilingual application, you will definitely need to customize the error message for that country. It doesn't take a rocket scientist to realise the need for customized message. And I would expect MVC team have that covered.
I'm working in a content development scenario where entities are likely to be created in an incomplete state and remain incomplete for some time. The workflow involved is extremely ad-hoc, preventing me from using a more structured DDD approach.
I have a set of validation rules which must be satisfied at all times, and a further set of validation rules which must be satisfied before an entity is "complete".
I'm already using the built-in ASP.NET MVC validation to validate the former. What approaches could I use to capture the latter?
For example:-
public class Foo
{
public int Id { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
public int Id { get; set; }
[Required] // A Bar must be owned by a Foo at all times
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
[Required] // A Bar must have a working title at all times
public string WorkingTitle { get; set; }
public bool IsComplete { get; set; }
// Cannot use RequiredAttribute on Description as the
// entity is very likely to be created without one,
// however a Description is required before the entity
// can be marked as "IsComplete"
public string Description { get; set; }
}
There are different approaches you could use:
Have your model implement the IValidatableObject interface and perform conditional validation without using data annotations.
Write a custom validation attribute that will perform the conditional validation logic of the Description property based on the value of the IsComplete property.
Use Mvc Foolproof which already has the RequiredIf validation attribute defined for you so that you don't need to write it yourself.
Use FluentValidation.NET which allows you to express your validation rules in a fluent manner. Writing conditional validation rules using this library is not only elegant but very easy. It integrates nicely with ASP.NET MVC and also allows you to easily unit test your validation logic in isolation.
Personally I would go with the FV.NET but you could use any of the other approaches if it better suits your needs.
Ref. this Microsoft's official video:
http://www.asp.net/web-api/videos/getting-started/custom-validation
I downloaded the code and run it. It's fine.
Then, I remove all the client validation attributes(data-val-*) from the html file. It didn't work fine. I could not see the validation messages on the web page.
My question is how to regular the server side validation messages and how to display them as client-side validation.
Why would you delete the validation attributes? That's exactly what gets you the validation messages. To change the validation tests, you need to set the appropriate validation attributes on the model properties, e.g.,
[Required]
public string Genre { get; set; }
[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[StringLength(5)]
public string Rating { get; set; }
As described in this post on ASP.NET MVC 4 Model Validation.