Required validation on hidden field - validation

I am using client side validation on hidden field in asp.net MVC. I am using required validation using data annotations. I am trying to validate hidden field but it’s not working.
My Model
[Required(ErrorMessage = "From date is required")]
public DateTime? FromDate { get; set; }
My View
#Html.HiddenFor(m => m.FromDate, new { ID = "hfdFromDate" }
#Html.ValidationMessageFor(m => m.FromDate)
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.

As some have pointed the validation isn't performed because the "hidden" property is set.
I had the same issue and ended up using the style tag:
#Html.TextBoxFor(m => m.Foo, new { style = "visibility:hidden"})
The validation is then performed.

Added this line before form.valid().
form.data("validator").settings.ignore = "";
where form is your form element.
In my case :
var form = $("#myForm");

Related

Required Field Validation in ASP MVC using Kendo UI

I have a textbox and want to display the field is required when the form gets submitted. The error message do appear in case i click on the textbox and tab to go to next textbox. I have the 'Required' data annotation on my model like this:
[DisplayName("Shipment Number")]
[Required]
public string ShipmentNumber { get; set; }
My View looks like this:
<div class="col-sm-8">
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8"})
#Html.ValidationMessageFor(model => model.ShipmentNumber)
</div>
Oh, i also added these in $function:
$("form").kendoValidator();
$.validator.setDefaults({
ignore: ""
});
When i leave the textbox blank and submit the form, the form gets submitted without showing the error message i.e. 'The Shipment Number is required!'.
P.S: I also tried DataAnnotation:
[Required(ErrorMessage = "ShipmentNumber Is Required")]
Does anyone know how i can achieve this?
Update:
This fixed it:
Changes in Razor code to make textbox required and added required error message.
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8", data_required_msg = "Shipment Number is required!", required = "required" })
In button submit code in javascript, did this:
var validator = $(".form-horizontal").kendoValidator().data("kendoValidator");
if (validator.validate()) {
//code that needs to be executed if it is valid
}
Note: I also got rid of data annotation from modal class, #Html.ValidationMessageFor and $("form").kendoValidator code.
Try forcing the validation when you click your button:
// Validate the input when the Save button is clicked
$("#save").on("click", function() {
if (validator.validate()) {
// If the form is valid, the Validator will return true
save();
}
});
or
$("form").submit(function(event) {
event.preventDefault();
if (validator.validate()) {
status.text("Hooray! Your tickets has been booked!")
.removeClass("invalid")
.addClass("valid");
} else {
status.text("Oops! There is invalid data in the form.")
.removeClass("valid")
.addClass("invalid");
}
});
See http://docs.telerik.com/kendo-ui/framework/validator/overview

MVC 3 Razor and the display of null dates in forms

I have an MVC 3 website where I display dates in forms using:
<div class="editor-label control-label">
#Html.LabelFor(m => m.rrsfWoman.DateOfBirth)
</div>
<div class="editor-field controls">
#Html.EditorFor(m => m.rrsfWoman.DateOfBirth)
#Html.ValidationMessageFor(m => m.rrsfWoman.DateOfBirth)
</div>
The date of birth is defined in the rrsfWoman class as
public DateTime WomansDateOfBirth { get; set; }
My problem is that as the date of birth field has by default a value of MinDate. Is there a way I can supress the display of the date as 1/01/0001 without making the field nullable.
Thanks
Is there a way I can supress the display of the date as 1/01/0001
without making the field nullable.
The correct way to achieve that is to make the date nullable in your view model. If you don't do that later you will struggle with model binding as well because a non-nullable DateTime field cannot be bound to an empty string and you will have to write custom model binders and stuff to make it work. You will make your life miserable if you don't use view models.
This being said, if you want to go against good practices, you could define a custom editor template for the DateTime type that will perform the check and use an empty value but honestly I don't recommend you doing that:
~/Views/Shared/EditorTemplates/DateTime.cshtml:
#model DateTime
#if (Model == default(DateTime))
{
#Html.TextBox("", "")
}
else
{
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)
}
You could set the default value of WomansDateOfBirth explicitly like so:
private DateTime _womansDateOfBirth = DateTime.Now;
public DateTime WomansDateOfBirth
{
get { return _womansDateOfBirth; }
set { _womansDateOfBirth = value; }
}
Where DateTime.Now is your MinDate.
If the date field does not allow nulls and you want to force the user to enter a date.
IMO, the best way is to simply clear the input field after the form is built.
So add this little snip-it at the end of your view.
<script type='text/javascript'>
document.getElementById("DateOfBirth").value = "";
</script>

ASP.NET MVC3 Validation of nested view model object fields

I have a view model that looks like this:
public class VenueIndexViewModel : BaseViewModel
{
public VenueAddViewModel Venue;
...
}
public class VenueAddViewModel
{
...
[Required(ErrorMessage = "This field is required")]
public string State { get; set; }
...
}
In my view, I'm rendering a form with with a drop down list for this property like so:
using (var form = Html.BeginForm())
{
...
#Html.DropDownListFor(x => x.Venue.State, Model.GetStates())
#Html.ValidationMessageFor(x => x.Venue.State)
...
}
This works, but the problem is that the the Required attribute on the view model appears to be ignored. If I look at the HTML, the data-val-* attributes are missing as well.
<select id="Venue_State" name="Venue.State">...</select>
However, if I change the rendering to a textbox...
using (var form = Html.BeginForm())
{
...
#Html.TextBoxFor(x => x.Venue.State)
#Html.ValidationMessageFor(x => x.Venue.State)
...
}
I see the expected data-val-* attributes and the validation works:
<input data-val="true"
data-val-required="This field is required"
id="Venue_State" name="Venue.State" type="text" value="">
I should note that I have other view models elsewhere that use DropDownListFor with a flat view model (no nested objects) and the validation works fine there, so I'm thinking I've hit a bug in the MVC validation handling for drop down lists when using a nested view model. Can anyone confirm / advise?
As far as I know you can't have client side validation on nested objects. And a quick google search seems to confirm that.
http://forums.asp.net/t/1737269.aspx/1

Replacement for TextAreaFor code in Asp.net MVC Razor

Following is my model property
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
public string ShortDescription { get; set; }
And following is my corresponding View code
#Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" })
#Html.ValidationMessageFor(model => model.Product.ShortDescription)
And this is how it shows in the browser, the way i want.
Now, since there is a bug in Microsoft's MVC3 release, I am not able to validate and the form is submitted and produces the annoying error.
Please tell me the work around or any code that can be substituted in place of TextAreaFor. I can't use EditorFor, because with it, i can't use rows and cols parameter. I want to maintain my field look in the browser. Let me know what should be done in this case
In the controller action rendering this view make sure you have instantiated the dependent property (Product in your case) so that it is not null:
Non-working example:
public ActionResult Foo()
{
var model = new MyViewModel();
return View(model);
}
Working example:
public ActionResult Foo()
{
var model = new MyViewModel
{
Product = new ProductViewModel()
};
return View(model);
}
Another possibility (and the one I recommend) is to decorate your view model property with the [DataType] attribute indicating your intent to display it as a multiline text:
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
[DataType(DataType.MultilineText)]
public string ShortDescription { get; set; }
and in the view use an EditorFor helper:
#Html.EditorFor(x => x.Product.ShortDescription)
As far as the rows and cols parameters that you expressed concerns in your question about, you could simply use CSS to set the width and height of the textarea. You could for example put this textarea in a div or something with a given classname:
<div class="shortdesc">
#Html.EditorFor(x => x.Product.ShortDescription)
#Html.ValidationMessageFor(x => x.Product.ShortDescription)
</div>
and in your CSS file define its dimensions:
.shortdesc textarea {
width: 150px;
height: 350px;
}

mvc 3 view data validation

i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?
The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }
Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?
1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl

Resources