Validate the field in Asp.net MVC

How to allow validation in Asp.Net Mvc using model.

1>Add new project --> Name the poject-->Choose MVC platform .
    Mvc Architecture will create .
2> Open the Model-->Create new class name it  Employee Model
    Add a refrence at top of the class.
   using System.ComponentModel.DataAnnotations;
   using System.ComponentModel.DataAnnotations.Schema;


Here is the Example:-



 using System.ComponentModel.DataAnnotations.Schema;
use for Table attribute.




using System;

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Test.Areas.Admin.Models
{
    [Table("Employee")]
    public class Experience
    {

          [Key]
          public int Id { get; set; }

         
         [Required]
         [Range(0, Int32.MaxValue - 1)]
         public int EmpEnrollno {get;set;}

         [Required]
         public string Name { get; set; }

        [Required]
        [Range(18, 60, ErrorMessage = "Valid for 18 to 60 year old.")] 
        [RegularExpression(@"\d{1,3}", ErrorMessage = "Invaild Age")]
        public string Age {get;set;}


        [Required(ErrorMessage="Enter the  Mobile Number")]
        [StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", MinimumLength = 10)]

        public string Mobilno { get; set; }





       
[Required(ErrorMessage="Enter the  DOB")]

        [DataType(DataType.Date)]

        public datetime DOB {get;set;}



      

        [Required(ErrorMessage = "Please Enter the EmailId")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression("", ErrorMessage = "Email Id is not valid.")]


        public string EmailId {get;set;}





        
[DataType(DataType.Currency)]

        public decimal  Salary {get;set;}



        

[MaxLength(5)]
        [MinLength(1)]
        [RegularExpression("^[0-9]*$", ErrorMessage = "invalid pincode")]

        public string Pincode {get;set;}



      



        [StringLength(5)]

        public string Performance {get;set;}



        

[StringLength(12, MinimumLength = 6, 
        ErrorMessage = "Username must be between 6 and 12 characters.")]

        public string UserName{get;set;}



       
[Required]

        

[DataType(DataType.Password)]

        [ValidatePasswordLength]

        public string Password{get;set;}



        

[DataType(DataType.Password)]
        [Compare("Password", 
ErrorMessage = "Password does not match..")]

        public string ConfirmPassword{get;set;}

       

       

 [Required]
        
        [NotMapped]
        [ValidateFile]
        [Display(Name = "Upload Image")]
        public HttpPostedFileBase Photo { get; set; }

       



        
    }
}

Thank you.




Share this

Previous
Next Post »