0

In my ASP.Net mvc3 Razor project i have to implement date validation.My format for the same was dd-mm-yyyy.i tried in different way but none works fine .I need a simple one.My question is is there any regular expression for the same.

My Model Code

{
    [Table("tbl_Employee")]
    public class Employee
    {

        [Key]public int EmpId { get; set; }
        [Required(ErrorMessage="Employee First Name is Required")]
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        [Required(ErrorMessage="Employee Last Name is Required")]
        public string LastName { get; set; }
        public int Age{get;set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]

        public DateTime DateOfBirth { get; set; }
        public string Address { get; set; }
        public string Position { get; set; }
        public string Department { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime DateOfJoining { get; set; }
        public string EducationalQuali { get; set; }
        public string Experience { get; set; }
        public string Others { get; set; }


    }

View Code

<div class="col-lg-10" >@Html.TextBoxFor(model => model.DateOfBirth, new { @class = "form-control", placeholder = "Date/Month/Year" })</div>

I have used one placeholder to show the user that ""this was the format".But it is also creating problem from the user.how to solve this?

1 Answer 1

2

You can decorate the model property with RegularExpression Attribute Class with the following pattern,

^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$

It will validate following date formats,

  • dd/MM/yyyy
  • dd-MM-yyyy

The property value will be set valid if it satisfies the pattern. You can set the custom error message in ErrorMessage property.

[RegularExpression("^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$", ErrorMessage="")]
public DateTime DateOfBirth { get; set; }

This works well on both server and client side. For client side which is better for good user experience, do not forget to turn on the unobtrusive validation and include jquery.validation.js and jquery.validation.unobtrusive.js in your web page. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.