Model Validation for Date in ASP.NET MVC3 Razor - asp.net-mvc-3

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?

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. :)

Related

MVC 5 Conditional Validation

Once again plethora of similar questions and none I can find to help me, or one I can understand.
My struggle is very simple actually. In a register form , I need to validate a few fields IF country selected from a drop down is a specific one. If not , no additional validations are needed. Let's say the country code needs to be "XX" in order to check the fields for things like length, integer or not etc.
I'm very new to MVC (less than a week) and after working with Webforms for a while, even something this simple confuses me. Anyway, here my code pieces
RegisterViewModel(only relevant fields included)
public class RegisterViewModel
{
//
[Required]
[Display(Name="Ülke")]
public string CountryCode {get; set;}
//
//[RegularExpression(#"^[0-9]*$")]
[Required]
[Display(Name = "Posta Kodu")]
public string PostCode { get; set; }
[Required]
[EmailAddress]
[Display(Name = "İrtibat E-Mail Adresi")]
public string Email { get; set; }
//regular expression and string length validations should work only if a certain country is selected
[Required]
[RegularExpression(#"^[0-9]*$")]
[StringLength(11, MinimumLength = 8, ErrorMessage = "Vergi Numarası hatalı.<br/> Lütfen kontrol ediniz.")]
[Display(Name = "Vergi No")]
public string TaxIdNo { get; set; }
//
[Required]
[Display(Name = "Firma Yetkilisi T.C. Kimlik Numarası")]
public string UserCitizenIdNo { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Firma Yetkilisi Email")]
public string UserEmail { get; set; }
[Required]
[Display(Name = "Firma Yetkilisi Tel. No.")]
public string UserPhoneNumber { get; set; }
//
}
The country dropdown
#Html.Bootstrap().DropDownListFor(t => t.CountryCode, MVCUtility.DataTableToListItem((DataTable)ViewBag.CountryList, "Code", "Name")).HtmlAttributes(new { #style = "width:100%;" })
I came across HasSelfValidation on a question but sadly noticed it is retired. How can I make these work inside an if-like construct?
PS: We set the dropdown to a specific value, I need to check if it's changed or not too.

update modelobject in a controller

I am trying to update user in my model object
public ActionResult AddJob(JobQueue job,HttpPostedFileBase file)
{
job.User = "itdev";
TryUpdateModel(job)
if (ModelState.IsValid)//Always returns false
{
}
}
MODEL
public class JobQueue {
[Required]
[Display(Name="JobId")]
public string JobId { get; set; }
[Required] [Display(Name = "FileName")]
public string FileName { get; set; }
[Required]
[Display(Name = "Job Run Date")]
public DateTime JobRunDate { get; set; }
[Required]
[Display(Name = "Email")]
public string Mail { get; set; }
[Required]
[Display(Name = "User")]
public string User { get; set; }
I tried using TryUpdateModel(job) and UpdateModel(job) after assigning the values.Both of these does not seem to update the model because ModelState.IsValid return false.Can someone point me in the right directions?I am using MVC3
Thanks,
Sab
I may be wrong here, but I think job.User = "itdev"; should be sufficent to update the model without using the TryUpdateModel(job) thats how we do it in our site anyway. I have never need to use any method to actually update the model itself. Just assigned values manually.
It depends on how your model is setup I guess.
You should probably post the code for your model just in case my answer isnt helpful.

EF4 MVC3 model state validation

Using this model:
public class Cases
{
//case data model for call center
//implement lists for all related child tables too
[Key]
public int CasesID { get; set; }
public string CaseNumber { get; set; }
[Required(ErrorMessage = "Customer is Required")]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
[MaxLength(50)]
public string UserName { get; set; } //get user name from the aspnet membership
[Required(ErrorMessage = "Case Category is Required")]
public int CaseCategoryID { get; set; }
[Required(ErrorMessage = "Technician is Required")]
public int TechnicianID { get; set; }
public virtual Technician Technicians { get; set; }
[Required(ErrorMessage = "Engine Model is Required")]
public int EngineModelID { get; set; }
public virtual EngineModel EngineModel { get; set; }
[MaxLength(50)]
public string BMSWorkorder { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Status is Required")]
public string CaseStatus { get; set; }
[MaxLength(50)]
public string OpenedBy { get; set; }
[Required(ErrorMessage = "Opened Date is Required")]
[DataType(DataType.DateTime)]
public DateTime? OpenedDate { get; set; }
[MaxLength(50)]
public string ClosedBy { get; set; }
[DataType(DataType.DateTime)]
public DateTime? ClosedDate { get; set; }
[MaxLength(50)]
[Required(ErrorMessage="Caller First Name is Required")]
public string CallerFirstName { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Caller Last Name is Required")]
public string CallerLastName { get; set; }
[MaxLength(100)]
public string AdditionalContact { get; set; }
[MaxLength(10)]
[Required(ErrorMessage = "Qualified is Required")]
public string Qualified { get; set; }
public string Description { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "ESN is Required")]
public string ESN { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Mileage is Required")]
public string Mileage { get; set; }
[DataType(DataType.Date)]
public DateTime? DateInService { get; set; }
[MaxLength(50)]
public string ESTR { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "EDS is Required")]
public string EDS { get; set; }
[MaxLength(50)]
public string GensetSerialNumber { get; set; }
[MaxLength(50)]
public string GensetModelNumber { get; set; }
//child Case Notes records
public virtual ICollection<CaseNotes> CaseNotes { get; set; }
//child case attachment records
public virtual ICollection<Attachment> Attachments { get; set; }
//child case complaint records
public virtual ICollection<CaseComplaint> CaseComplaint { get; set; }
//tracking fields
public DateTime? CreatedOn { get; set; }
[MaxLength(50)]
public string CreatedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
[MaxLength(50)]
public string ModifiedBy { get; set; }
}
I am wondering why even though only some of the properties are marked required, the modelstate does not get set valid unless all properties have values when saving.
Am I doing something wrong?
EDIT
Here are my razor elements for the dropdownlist fields in question:
#Html.DropDownList("Qualified", String.Empty)
#Html.ValidationMessageFor(model => model.Qualified)
#Html.DropDownList("EngineModelID", String.Empty)
#Html.ValidationMessageFor(model => model.EngineModelID)
#Html.DropDownList("CaseCategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.CaseCategoryID)
The EngineModelID and CaseCategoryID properties must be nullable integers on your view model if you want to allow empty values. Oooops, you are not using view models.
ASP.NET MVC automatically makes non-nullable types required. You could disable this explicitly in your Application_Start:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
But if you want to do the things properly you should use view models.
The following is absolutely horrible:
#Html.DropDownList("CaseCategoryID", String.Empty)
I guess you have stuffed a SelectList in a ViewBag.CaseCategoryID so the CaseCategoryID does 2 things at the same time: it represents a list and a selected scalar value.
With view models you would use the strongly typed version of those helpers:
#Html.DropDownListFor(x => x.CaseCategoryID, Model.CaseCategories)
where CaseCategories will be an IEnumerable<SelectListItem> property on your view model that the controller would populate.

The 'SubCatNewsID' property on 'SubCatNews' could not be set to a 'Boolean' value. You must set this property to a non-null value of type 'Int32

I'm getting this error some time, without any action I do
This appears at random
I use this frameworks:
Entity in CodeFirst type,Mvc3
Sometimes I get this erros in diffrent data types or for other models:
The 'CatID' property on 'Cat' could not be set to a 'Boolean' value. You must set this property to a non-null value of type 'Int32
or
The 'CatID' property on 'Cat' could not be set to a 'String' value. You must set this property to a non-null value of type 'Int32
my site subject is news publishing and my client operators work with site and insert/edit data During all off day
Edit:
i see that this erros is not for a page,when i have this error,no page in my site not load and all of the pages have this message
my model:
public class SubCatNews
{
[Key]
public int SubCatNewsID { get; set; }
// [EdmScalarPropertyAttribute(IsNullable = true)]
// public int? SubCatID { get; set; }
[Required(ErrorMessage = "some error")]
public string Title { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Summary { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Details { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? ImpStatus { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? Created { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? Visible { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public string pic { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? UsersID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? StatusID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? NewsTypeID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? ZonesID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? lanID { get; set; }
//public int RatingSubCatNewsID { get; set; }
public virtual Users Users { get; set; }
// public virtual SubCat SubCat { get; set; }
public virtual NewsStatus Status { get; set; }
public virtual NewsType NewsType { get; set; }
public virtual ICollection<SubCatNewsComment> SubCatNewsComments { get; set; }
public virtual ICollection<NewsInSubCat> NewsInSubCatss { get; set; }
public virtual ICollection<SubNewsInTag> SubNewsInTags { get; set; }
//public virtual RatingSubCatNews RatingSubCatNews { get; set; }
}
But i`m wondering that when i make any change in web.config,site is up!
i thing this is for caching data and values in Entity
my Context Creator:
public abstract class BaseController<TEntityType, TIdType> : ContextGridController<HNewsPortalContext, TEntityType, TIdType>
where TEntityType : class
{
protected override HNewsPortalContext CreateContext()
{
return new HNewsPortalContext();
}
}
before this time,my Context Creator,return Context like this:
HNewsPortalContext.Singleton;
i guess this was for static context and entity caching make this error,but newing context,do not fix my error
now when my site have this error,i make a little change(switch Custom Error Mode value between Off or RemoteOnly) in web.config and save it,then site is up
please help me
tanx
my full error message:
full message image
full message image
Attach debugger, break on exception and check the stack trace to see what code is setting your properties.
i checked and see that was because overflowing my application pool
my site was on a shared server and session expire time was very long
finish

ASP.NET MVC3 Eager Client-Validation, FluentHTML and Nested ViewModels

I'm using FluentHTML (from MvcContrib) to layout my HTML mark-up. I want to use eager unobtrusive client-validation provided by jquery.validate library. I got everything working correctly except for properties of nested ViewModels. Example:
public class RegisterPageViewModel
{
[Required(ErrorMessage = "First Name cannot be empty.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name cannot be empty.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email cannot be empty.")]
[RegularExpression(#"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Invalid Email Format.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password field cannot be empty.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "You have to confirm your password.")]
[Compare("Password", ErrorMessage = "Passwords must match.")]
[DataType(DataType.Password)]
public string PasswordConfirm { get; set; }
[Required]
public AddressDto Address { get; set; }
public bool TermsOfUse { get; set; }
[Required(ErrorMessage = "Nickname is required")]
public string Nickname { get; set; }
public string MiddleName { get; set; }
[Required(ErrorMessage = "Birthdate is required")]
public string Birthdate { get; set; }
public string Phone { get; set; }
[Required(ErrorMessage = "Mobile number is required")]
public string Mobile { get; set; }
public string RakimMelieh { get; set; }
public string ReferralNickname { get; set; }
}
It works perfectly for ALL of the properties except for those inside the Address property, although I decorated the properties of the AddressDto with validation attributes as well:
public class AddressDto
{
public int Id { get; set; }
[Required(ErrorMessage = "Address Name is required.")]
public string Name { get; set; }
public string Country { get; set; }
public string District { get; set; }
public string City { get; set; }
public string Area { get; set; }
[Required(ErrorMessage = "Address Details are required.")]
public string Details { get; set; }
public bool IsDefault { get; set; }
}
The same thing happens for other view models as well where there are nested view models inside them. One thing I noticed when inspecting the input fields FireBug is that they always have the valid class on them, even when they're not really valid (according to the annotations decorating their properties).
Any thoughts how I can solve this problem?

Resources