Data Annotations
Ref: http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-6
- Required – Indicates that the property is a required field
- DisplayName – Defines the text we want used on form fields and validation messages
- StringLength – Defines a maximum length for a string field
- Range – Gives a maximum and minimum value for a numeric field
- Bind – Lists fields to exclude or include when binding parameter or form values to model properties
- ScaffoldColumn – Allows hiding fields from editor forms
Code: https://github.com/jasonccliu/mvcdemo/commit/2180812eb8570357240cdf845984d08e61ffb3d4
呈現名稱
[Display(Name="First Name")]
必要欄位
[Required(ErrorMessage="Please provide First Name", AllowEmptyStrings = false)]
電子郵件
[EmailAddress]
Useful Resources
http://www.c-sharpcorner.com/article/data-annotations-and-validation-in-mvc/
http://www.c-sharpcorner.com/blogs/validation-in-asp-net-mvc-using-dataannotations
https://www.c-sharpcorner.com/article/dataannotations-in-depth/
-- 用客製屬性方式來檢查使用者輸入的資料及格式
-- MetaData
[ApplicationOwnerContactAttribute(false, ErrorMessage = "The {0} isn't valid")]
public string AppOwnerContact;
public class ApplicationOwnerContactAttribute : ValidationAttribute
{
private bool ThrowExcepcion;
public ApplicationOwnerContactAttribute(Boolean isThrowException)
{
ThrowExcepcion = isThrowException;
}
public override bool IsValid(object value)
{
try
{
Worker wrkr = new Worker(value.ToString());
if (wrkr == null || wrkr.FullName == null)
{
if (ThrowExcepcion)
throw new ArgumentException(
"The user account is incorrect!");
else
return false;
}
}
catch (Exception)
{
return false;
}
return true;
}
}