MVC 5 Conditional Validation - 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.

Related

Model Validation for Date in ASP.NET MVC3 Razor

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

Multiple views same model[MVC 3]

I have one model and one controller for multiple views.
The model have some required fields but for a specific view i need to ignore the validation for 2 specific fields.
There is any method to ignore the validation for those 2 fields?
I am using asp.net MVC3.
Model code example:
[Required(ErrorMessage = "Campul strada este obligatoriu")]
public string Strada { get; set; }
[DisplayName("Numar strada")]
[Required(ErrorMessage = "Campul strada numar este obligatoriu")]
public string NrStrada { get; set; }
For 9/10 views that is ok but for 1 view i don't want to be requiered.
When such an issue occurs then I normally create different view models. Each with it's own validation logic. There's nothing wrong with doing it this way.
Here are examples, not relating to your code, you can adjust your code accordingly.
For example with create customer I would have a create customer view model, and for edit customer I would have a edit customer view model. Each has different sets of validation. Create customer only requirs a first name and a last name. Edit customer needs a first name, last name, and employee number of who updated the customer record. Employee number updater is not required when adding a new customer.
Here is a possible create customer view model:
public class CreateCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
}
Here is a possible edit customer view model:
public class EditCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Required")]
public string UpdatedByEmployeeNumber { get; set; }
}
This is just a basic example.

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.

Update decimal numbers when using other local

I have this Model
public class SalesModelView
{
[Key]
public int SaleId { get; set; }
public int ShopId { get; set; }
public string ShopName { get; set; }
[Display(Name = "Date")]
public DateTime SaleDate { get; set; }
[Required]
[Display(Name = "Timer")]
[Range(0, 24)]
public int Hours { get; set; }
[Required]
[Display(Name = "Salg")]
public Decimal Sales { get; set; }
[Required]
[Display(Name = "Behandlinger")]
public Decimal Treatments { get; set; }
[Display(Name = "Omsætning")]
public Decimal Turnover { get; set; }
[Display(Name = "Oms./Timer")]
public Decimal TurnoverHour { get; set; }
[Display(Name = "Effektivitet")]
public Decimal Efficiency { get; set; }
}
and in Danish locale a decimal normally shows as 280.800,00, so . as thousands and ,as decimal place.
My view shows the correct stuff
But when saving back to my model, I get the . as a decimal separator, passing all the values to:
(original image for better visualization)
So the number 546.400 is converted to 546,4
I already tried with no luck to hook up the form submit and replace all . with nothing, like
$("form").bind("submit", function() {
$(".number").each(function(){
var v = $(this).val(v).replace('.','');
$(this).val(v);
});
});
What technique do you guys use for this kinda things?
P.S. I did read Hanselman's article but I still got the exact same problems, it's when I pass it to the Controller that goes wrong, all is well in the View
The DefaultModelBinder doesn't work well in these situations. You could write your own or make sure to submit en-US values. Here is an article talking about it.
Model Binding Decimal Values

MVC 3 Binding Dynamic View Data to Model

I'm not sure if I created this topic correctly, but basically I have a number of text fields and drop downs in my view and they are arranged in such a way as to look like a row. Some of the fields include Weight, Height, Length, etc. and the fields together compose a logical item. When the user clicks on a button next to the row it dynamically creates a new row of the same textfields and dropdowns, thus adding another "item" to the form. My question is how do you get the new rows to bind to a property in the model? So for example here are the fields in the model:
[Required]
[Display(Name = "Weight")]
public string Weight { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Class")]
public string Class { get; set; }
[Required]
[Display(Name = "Number of Units")]
public string NumberOfUnits { get; set; }
[Display(Name = "Length")]
public string Length { get; set; }
[Display(Name = "Width")]
public string Width { get; set; }
[Display(Name = "Height")]
public string Height { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Type")]
public string Type { get; set; }
If the user only uses the first row this is fine since it properly maps the textfields and dropdowns to the model, but adding an additional row of these elements won't work as far as the model is concerned. Any ideas on how to get the model to bind to the dynamically created elements? Thanks.
I would recommend you the following blog post. It explains in details how to achieve this.

Resources