I am using ASP.Net Core Razor pages and have a form on which the end date must be validated on the client side to be later than the start date.
The rest of the form is being validated using UoN.ExpressiveAnnotations.
The dates are defined as follows :
[Display(Name = "Start Date")]
[Required]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[Required]
public DateTime? EndDate { get; set; }
I have tried using
[RequiredIf("EndDate > StartDate", ErrorMessage = "End must be later than Start")]
with the End Date declaration, but this does not provide the validation necessary.
Am I missing something obvious?
Thanks
DOH. I was missing something obvious.
It should have been
AssertThat
not
RequiredIf
Related
I have this property on the MVC5 viewmodel with the StringLength validation attribute:
[Required]
[StringLength(4, MinimumLength = 4, ErrorMessage = "The postcodes must be 4 characters long.")]
[Display(Name = "Postcode (four digits)")]
public int Postcode { get; set; }
The client-side validation works, but when I execute the action by submitting the form I am getting this error:
Unable to cast object of type 'System.Int32' to type 'System.String'.
I know it is the attribute that's causing this because everything works when I comment out the [StringLength] attribute.
I suspect that this is to do with the fact that the property type is int. But how to specify string length validation of an integer property? Is putting string type in ViewModel and then parsing it to int in the controller the best solution or is there an attribute for that? At attribute-driven solution would be nice.
EDIT: I tried [DataType(DataType.PostalCode)] but it didn't work.
Thanks.
DataType attributes can't be used to validate user input. They only provide hints for rendering values using templated helpers.
The range is a perfect validation for int's.
[Required]
[Range(1000,9999, ErrorMessage="The postcodes must be 4 characters long.")]
[Display(Name = "Postcode (four digits)")]
public int Postcode { get; set; }
int uses range, strings use string length, you cannot convert string length to int. [DataType(DataType.PostalCode)] will only work with a string. for postal code you can do a few things.
I suggest to make it a string.
i would make it a string with RegularExpression:
[Required(ErrorMessage = "Postal Code is Required")]
[DataType(DataType.PostalCode)]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Postal Code Invalid.")]
[Display(Name = "Postcode (four digits)")]
public string Postcode { get; set; }
In my web application (asp.new mvc) I try to make validation for date field.
If I use this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
or this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
it works. But if I try to separate using '.' separator
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
I have an issue. jQuery validation says that I have to enter date if I try '01.01.2001'.
Here is view
<div class="ElementDiv">
#Html.LabelFor(m => m.Filter.PeriodBeginFrom, new { #class = "Labels" })
#Html.EditorFor(m => m.Filter.PeriodBeginFrom, new { #class = "TextBoxes" })
#Html.ValidationMessageFor(m => m.Filter.PeriodBeginFrom, null, new { #class = "Errors" })
</div>
Why? With all other separators it works. What a problem is with '.' separatior?
Update 1: It seems that validation does not work properly. If I have this attribute at my model
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
and we pass DateTime object to model, it will be displayed at textbox with '.' like '12.12.2012' and not like I was waiting '12/12/2012'. Hope you'll give me some ideas.
You're looking at a date component. But remember that time components can include seconds and fractional seconds, with a period inbetween. Since dates and times are frequently combined, I would not be surprised if the period is being treated as a special character.
Update:
I went through the following documentation chain:
DisplayFormatAttribute.ApplyFormatInEditMode Property
DisplayFormatAttribute.DataFormatString Property
Formatting Types
Custom Date and Time Format Strings
I expected to see that the period character has a special meaning in the format string. Instead, the documentation doesn't specifically list the period character. That means it should fall in the categry of "Any other character", and therefore, "The character is copied to the result string unchanged."
However, I don't believe it. Fractional seconds occur in time components like 23:59:59.999, and I suspect there is undocumented special treatment of the period character.
Trouble with a format was not with ASP tags and fields but with unobtrusive validation jquery library. I had to overload unobtrusive JavaScript validation method for date for my date format. More details are here
MVC DateTime validation - UK Date format
I have a ViewModel with a String property and the following Data Annotation :
Edit to work with string
[DataType(DataType.Date, ErrorMessage="Not Working !!!")]
public String StringBirthDate1 { get; set; }
That's my view
#Html.EditorFor(model => model.StringBirthDate1 )
#Html.ValidationMessageFor(model => model.StringBirthDate1)
If I run my application and put an invalid Date like '---' or 29.02.1900 I don't get any validation error !
Ok I've given up trying to use built-in MVC tools for data validation !
I did a custom Validation Attribute :
public class ValidDateStringAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime dtout;
if (DateTime.TryParse(value.ToString(), out dtout ))
{
return true;
}
return false;
}
}
Here is my View Model decorated with the custom attribute :
[ValidDateString(ErrorMessage="Invalid date format")]
public String BirthDate1 { get; set; }
Works like a charm :-)
It seems to me, that [DataType(DataType.Date, ErrorMessage="Not Working !!!")] working when it attached to string property. Try to use:
[DataType(DataType.Date, ErrorMessage="Not Working !!!")]
puplic string StringBirthDate1{get;set;}
public DateTime BirthDate1
{
get{return DateTime.Parse(StringBirthDate1);}
set{StringBirthDate1 = value.ToString();}
}
I didn't like any of the solutions I found so I kept poking at possibilities until I came up with one I do like. I added a regular expression validator utilizing the regular expression from this article: http://answers.oreilly.com/topic/226-how-to-validate-traditional-date-formats-with-regular-expressions/
[Required(ErrorMessage = "Birthdate is required. [MM/DD/YYYY]")]
[RegularExpression(#"^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$", ErrorMessage = "Birthdate must be in MM/DD/YYYY format.")]
public Nullable<DateTime> Birthdate { get; set; }
The result is, if the field is blank I get the required error message and if anything is in the field, but it is not a valid date, I get the regular expression message.
I might add that it seems very silly that [DataType] doesn't accept an error message. I tried exactly like the original author of this thread. That would have been logical and intuitive.
I am developing an ASP.Net MVC 3 Web Application using Razor Views. Within the View I would like to ask the user a question which can only have a Yes/ No answer, therefore, I am planning on using two Radio Buttons.
I have a ViewModel which I pass to my View, and it looks like this
public class ViewModelFormImmigration
{
public int immigrationID { get; set; }
public int formID { get; set; }
[Required(ErrorMessage = "Please select Yes or No.")]
public bool euNational { get; set; }
}
In my View I then have the following lines of code to display the radio buttons for both the Yes and No options
#Html.RadioButtonFor(model => model.euNational, true) <text>Yes</text>
#Html.RadioButtonFor(model => model.euNational, false) <text>No</text>
My problem is that, when the User comes to this View for the first time, I would like neither the Yes or No option selected. At the moment, when I create an instance of my ViewModel (see above), the property euNational is defaulted to false and when the ViewModel is passed to my View, this means that the option No is automatically selected.
Is there anyway around this so that when the User see's the View for the first time, that no option is not selected by default?
Thanks for your help everyone.
Try changing:
[Required(ErrorMessage = "Please select Yes or No.")]
public bool euNational { get; set; }
To:
[Required(ErrorMessage = "Please select Yes or No.")]
public bool? euNational { get; set; }
This way, when you first load the view with no value set for euNational it will not set to neither true or false. As at the moment when it has no value set, it defaults to false
I'm using asp.net MVC 3 with razor view engine on my app.
What happens is, for example when my model has a date field and someone writes something that is not a valid date o get a message like "The value 'asd' is not valid for StartDate",
I don't know how to localize this message for example to get it on Portuguese "Data inĂ¡lida".
Can someone help?
You must set the right attributes on your Model class. Like this:
[Date(ErrorMessageResourceName = "RequiredStar", ErrorMessageResourceType = typeof(Properties.Resources))]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "RequiredStar", ErrorMessageResourceType = typeof(Properties.Resources))]
[DataType(DataType.DateTime)]
[Display(Name = "Birthday", ResourceType = typeof(Properties.Resources))]
[UIHint("Date")]
public DateTime Birthday { get; set; }