Sunday 31 May 2015

Data Notation with MVC 5

Here is the sample for validation with MVC


[MetadataType(typeof(UserDetail.Metadata))]
    public partial class UserDetail
    {
        private sealed class Metadata
        {
            //making id as Hidden filed
            [HiddenInput(DisplayValue = false)]
            public int UserId { get; set; }

            [DisplayName("Email Address")]
            [Required(ErrorMessage = "Please enter Email ID")]
            [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
            public string EmailID { get; set; }

             [StringLength(100, MinimumLength = 4)]
            [Required(ErrorMessage = "Please enter First Name")]
            public string FirstName { get; set; }

            [Required(ErrorMessage = "Please enter Last Name")]
            public string LastName { get; set; }

            [Required(ErrorMessage = "Please enter Age")]
            [Range(18, 100, ErrorMessage = "Age must be between 18 and 100")]
            public string Age { get; set; }

            public Nullable<bool> IsActive { get; set; }

        }
    }

Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>




No comments:

Post a Comment