How to validate date properly in mvc 3? - asp.net-mvc-3

I want to validate the date properly.If Iam entering the date as 21-2-198 instead of 21-2-1988
.The date is not validating properly in Mvc3.I used Regex for this but didn't be useful.Is any other method to validate the date including the year in MVC model.Following is the code i written in the model
[Required(ErrorMessage = "Activation date is required")]
[Display(Name = "Activation date")]
[RegularExpression(#"/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/", ErrorMessage = "Enter proper date")]
public DateTime? ActivationDate { get; set; }

you should be able to get validation by using the [DataType(DataType.Date)] attribute instead of your regular expression. Note that this Annotation is locale agnostic... i.e. 21-2-1988 and 2-21-1998 will both validate.

Iam entering the date as 21-2-198 instead of 21-2-1988 .The date is not validating properly in Mvc3.
It seems to me that you need a CustomValidator that prevents user to enter a date out of specific range.
ASP.NET MVC 3 Custom Validation using Data Annotations presents a Validator for this purpose.

Related

Telerik asp.net for MVC datepicker format in grid related issue

I have specified date format as dd/mm/yyyy for telerik datepicker. However, it is recognized as mm/dd/yyyy only. For example, if i enter date as 18/10/2012 error on saving record is thrown as date format is not valid as date entered here as 18 is treated as month. I have defined view for date as:
#model DateTime?
#(Html.Telerik().DatePickerFor(m => m)
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty))
.Format("dd/MM/yyyy")
.HtmlAttributes(new { id = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty) + "_wrapper" })
.InputHtmlAttributes(new {style="width:160px;"}))
And in model validation for date field is defined as:
[Required(ErrorMessage = "Date Required")]
[DataType(DataType.Date)]
public DateTime? DATE_CALL { get; set; }
Also, in grid has defined column as:
col.Bound(r => r.DATE_CALL).Format("{0:dd/MM/yyyy}").Title("DATE_CALL").Width(170);
So, can't figure out what the error is? Any help will be appreciated.
use the following to set your date format before saving to the database:
DateTime.ParseExact(<yourDate>, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Date Fails Client and Server Side Validation Using ASP.NET MVC 3 Data Annotations

In all my projects, I have jQuery date pickers that format the date dd-MMM-yyyy
which both users worldwide and the DateTime.parse method understand perfectly - sadly this does not appear to be the case for data annotation validation! I have my data annotation as below:
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "You must enter a date of birth.")]
public DateTime dob { get; set; }
And my form refuses to submit with the error as below:
Does anyone know how I can make it validate, accept and modelbind a date value in this format?
You could write a custom model binder for the DateTime type as I have shown here that will use the format defined in the [DisplayFormat] attribute when parsing back a DateTime field from the request. By the default the model binder uses the CultureInfo setting of the current thread or the value you have configured in the <globalization> element of your web.config. If you set it to auto, then ASP.NET will use the client Accept-Language request header to adjust the culture info.

JQuery Validation and MVC 3. How to change date format

I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.
My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?
My view model has a field
[Required]
DateTime OrderDate { get; set; }
I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.
Thank you.
When you use client side validation for date, you have to override the jQuery validation for date as well.
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}
You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.
If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:
[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }
Where the DataFormatString is your desired date time format.

MVC3 Attribute validation question

I'm getting odd behavior with my validation in my view.
My model has this property.
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
public decimal OverFlowCapacity { get; set; }
My view has this:
<tr>
<td>#Html.LabelFor(m=> m.OverFlowCapacity)</td>
<td>#Html.EditorFor(m=>m.OverFlowCapacity)</td>
<td> #Html.ValidationMessageFor(model => model.OverFlowCapacity)</td>
</tr>
If I enter a value like 'ABC', I get the validation message 'Number required'
If I enter a value of 999999, I get the validation message 'Value must be between 0 - 9,999.99'
Both of those messages are received when I tab off the text box as expected.
When I leave the text box value empty and tab off, I get no errors, as expected.
However, when I submit, I get a validation message 'The Overflow Capacity field is required.'
I don't know where this is coming from. I've tried removing all validation attributes from the model, and still get the 'required' message. I'm at a loss.
Here are the scripts I've referenced.
I have other issues with mvcfoolproof that I may post later. I'm wondering if this isn't somehow responsible for my problems.
What's happening to you now is the post validation is kicking in after the form has been submitted and determining that the decimal value cannot be null. Right now you are using a decimal type which is non-nullable. If you want this behavior and you want to see the validation before you submit the form then add the [Required] attribute to the property. However if you don't want this functionality and it can possibly be null, then change your type from decimal to decimal? or Nullable<decimal>.
Don't allow nulls and have the pre-submit validation:
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
[Required]
public decimal OverFlowCapacity { get; set; }
Allow nulls and get rid of post-submit validation error:
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
public decimal? OverFlowCapacity { get; set; }
Since you're not marking your decimal type as nullable, MVC doesn't know what to do with the empty field you're posting back. Try this if you want to allow nulls/empty fields:
public decimal? OverFlowCapacity { get; set; }
and try this if you want it to have a pre-submit validation message requiring the field to be filled in:
[Required]
public decimal OverFlowCapacity { get; set; }
Answers above explain Required error message quite well so i will just focus on second error message. i.e if you put 'abc' jquery tells you "Number Required". How does jquery know that this input should only accept number fields. The answer is; through unobtrusive attributes that are generated with form fields. If you inspect input field you will find something like
<input name="OverFlowCapacity" id="OverFlowCapacity" data-val-number="Number Required"..../>
so to override this default validation message you have to decorate your model with the attribute that does the exact same thing (number validation) and their you can override the validation message
[Numeric(ErrorMessage="override message")]
[Required(ErrorMessage="override Required message")]
public decimal OverFlowCapacity{get;set;}
I doubt Numeric attribute is present in DataAnnotation or mvc framework. you have to check into that. There are some useful attributes discussed and available here

mvc 2.0 validation

I am use DataAnnotations validation, it work perfectly but when I validate empty text box field I have error
The value '' is invalid
how can I customize this error?
p.s.
error shows only when clients script are off
You can specify the error message in your DataAnnotations attribute. For example, take the following view model:
public class ViewModel
{
[Required(ErrorMessage = "You must enter a name")]
public string Name { get; set; }
}
When that gets validated, it will give "You must enter a name" as the error message to the user.

Resources