Intent of Data Annotations Model Binder - asp.net-mvc

The article here mentions the use of Data Annotations Model Binder that is available here.
Does anyone know what it's intent is? To do DA validation, I don't need a special Model binder in MVC 2.0

The first release of ASP.Net MVC didn't support validation via Data Annotations as part of the framework. The intent of the linked codeplex code was to specifically allow usage of attribute oriented validation (which was in high demand) as a stopgap to the solution that was implemented in the second release.

DataType
Specify the datatype of a property
DisplayName
specify the display name for a property.
DisplayFormat
specify the display format for a property like different format for Date proerty.
Required
Specify a property as required.
ReqularExpression
validate the value of a property by specified regular expression pattern.
Range
validate the value of a property with in a specified range of values.
StringLength
specify min and max length for a string property.
MaxLength
specify max length for a string property.
Bind
specify fields to include or exclude when adding parameter or form values to model properties.
ScaffoldColumn
specify fields for hiding from editor forms.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
[Bind(Exclude = "EmpId")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmpId { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100,MinimumLength=3)]
public String EmpName { get; set; }
[Required(ErrorMessage = "Employee Address is required")]
[StringLength(300)]
public string Address { get; set; }
[Required(ErrorMessage = "Salary is required")]
[Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
public int Salary{ get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(#"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string Email { get; set; }
}
}

Related

In ASP.NET MVC, how to set one error message for all required fields in class without copy/paste?

I have the following model:
public class Human
{
[Required]
[StringLength(50)]
[Display(Name = "First Name")]
public String FirstName { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Last Name")]
public String LastName { get; set; }
// 50 more required fields not shown for brevity
}
If a user doesn't fill out a required field, I would like the error message to be "This field is required". However, I don't want to annotate every single one with [Required(ErrorMessage = "This field is required")] because that takes a lot of copy/pasting.
Is there a way to tell ASP.NET MVC that all required fields in ONLY THIS CLASS should have the error message "This field is required"?
I did not find a way to accomplish this. I think it is not possible.

How to force users to register with e-mail in ASP.NET MVC 4? [duplicate]

This question already has answers here:
Email address validation using ASP.NET MVC data type attributes
(12 answers)
Closed 8 years ago.
I want to force users to register with their e-mail addresses DataType.EmailAddress doesn't work.
public class RegisterModel
{
[Required]
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
...
}
Any help is appreciated.
If your wanting validation for an email address, you need the [EmailAddress] attribute (NET 4.5)
[Required]
[Display(Name = "E-mail")]
[EmailAddress] // Add this
public string UserName { get; set; }
or for NET 4.0 you can use a [RegularExpression] attribute (this one is taken from jquery-validate 1.9.0)
[Required]
[Display(Name = "E-mail")]
[RegularExpression(#"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$", ErrorMessage="Please enter a valid email adress")]
public string UserName { get; set; }
Note the [DataType] attributes are used by #Html.EditorFor() to render the type attribute used by browsers (e.g type="email")
You can use the "EmailAddress" annotation:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string UserName { get; set; }
EDIT:
For MVC 4 and below, you can use regex expression to do validation on Email address fields.
See more here:
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

How to display two different error message in ASP.NET MVC4

I want to display two different error message. First give for required and second for Int64 value. Here is my code.
[Display(Name = "Employee")]
[Required]
public Int64 EmployeeId { get; set; }
You can use the RangeAttribute.
[Required(ErrorMessage = "Msg1")]
[Range(10, 1000,
ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public object Weight;
You can use data annotation extentions here: http://dataannotationsextensions.org/
Then add the two annotations as follows:
[Required(ErrorMessage = "Employee Id is required")]
[DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")]
public Int64 EmployeeId { get; set; }

Why does adding EmailAddressAttribute to a property causes EditorFor to fail?

I have a string property on my model object called EmailAddress. I'm using Html.EditorFor to render input fields for all string properties on this page, and a custom editor template which works fine. However, the minute I add the EmailAddressAttribute to this property, EditorFor appears to no longer detect the property as a string type, or at least, it refuses to use the editor template I have for strings.
This works:
[DisplayName("EmailAddress")]
[Required(ErrorMessage = "Required")]
[StringLength(100, ErrorMessage = "Must be <= 100 characters.")]
public string EmailAddress { get; set; }
// and then in my view...
#Html.EditorFor(x => x.EmailAddress)
This does not:
[DisplayName("EmailAddress")]
[Required(ErrorMessage = "Required")]
[StringLength(100, ErrorMessage = "Must be <= 100 characters.")]
[EmailAddress(ErrorMessage="Invalid email address.")]
public string EmailAddress { get; set; }
// and then in my view...
#Html.EditorFor(x => x.EmailAddress)
In the second example, the default string editor template is used instead of my own. Other properties on the same model render using the correct editor template.
Am I missing something obvious or does this seem like a bug?
The [EmailAddress] attribute sets the property's DataType to EmailAddress, which causes EditorFor() to look for an EmailAddress template.

MongoDB C# - Hide property from serializer

This is what my user model looks like:
namespace Api.Models
{
public class User
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRequired]
public string Id { get; set; }
[Required(ErrorMessage = "Username is required.")]
[StringLength(20, MinimumLength=3, ErrorMessage="Username must be between 3 and 20 characters.")]
[BsonRequired]
public string Username { get; set; }
[Required(ErrorMessage="Email is required.")]
[EmailAddress(ErrorMessage="Valid email required.")]
[BsonRequired]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required.")]
[StringLength(50, MinimumLength=8, ErrorMessage="Password must be between 8 and 50 characters.")]
[BsonRequired]
public string Password { get; set; }
[BsonRequired]
public string Salt { get; set; }
}
}
I want to write, and require, all of the properties into the MongoDB Database. What I don't want to do, is expose the Password and Salt properties when I send this through the request.
Is there any sort of data attribute that I can set that will write it, but not expose it when displayed to any API user?
The correct approach is to use view models. Don't pass your domain entities to the views. Design view models that meet the specific requirements of your views. So for example design a view model that doesn't have the Password and Salt properties because that's what this view needs. Then in order to ease the mapping between your domain models and view models you could use AutoMapper.
If you don't want to follow good practices with view models you still have the possibility to clutter your POST actions with the Bind attribute and decide which properties you want to be included/excluded from model binding. For example:
[HttpPost]
public ActionResult SomeAction([Bind(Exclude="Password,Salt")]User user)
{
// at this stage the Password and Salt properties will always be null =>
// they will never be bound from the request even if the user attempts to
// forge an HTTP request and include them
...
}

Resources