MVC 3 [If then else] custom Validation with JavaScript - asp.net-mvc

I'm having a problem doing custom validation.
Assuming I have the following class:
// begin example
class vehicle
{
prop bool Car { get; set; }
prop string RegistrationID { get; set; }
prop int numberOfSeats { get; set; }
}
// end example
I want to have validation that: If the property Car is true, then the numberOfSeats is required, else the numberOfSeats is not required and the corresponding textbox is disabled.
Based on the class, I have a stronglyTyped view where I use the HTML helpers.
I've been reading several articles about validations, including this link but cannot find the solution.
To make the above validation, it is best to create a custom control, since I have to validate and depend on the property Car. I disable and enable a textbox (property numberOfSeats) ?

The project at http://foolproof.codeplex.com/ includes a [RequiredIfTrue] custom validator which seems to fit what you're looking for. You'd have to disable/enable the textbox yourself, though.

Related

ASP.NET MVC - Dynamic Forms Validation

I'm in the process of upgrading an ASP.NET WebForms application to ASP.NET MVC. One of the features on the existing application is it has a dynamic form generator. Each form has steps (using the wizard control that are dynamically added in the Wizard_Init event) and validation (using the validation controls).
I already have some static MVC forms where I use data annotation attributes on my model properties and then use the in-built unobtrusive validation to validate the form.
Now say I have the following model:
public class Form {
public string Name { get; set; }
public IList<Step> Steps { get; set; }
}
public class Step {
public string Name { get; set; }
public IList<Field> Fields { get; set; }
}
public class Field {
public string Name { get; set; }
public bool IsRequired { get; set; }
}
Obviously the fields are dynamic so I can't use the data annotation attributes. Also I only wish to validate each step. One option I thought was to render all the steps within the form and show/hide the appropriate step using javascript as they click next/previous. But again I can't see how I can add validation to this. Another option is to load in each step using Ajax but again I'm struggling with this concept.
I'd really appreciate it if someone could help. Ideally I'd like advice on the best way to achieve this rather than linking to an old third party library unless it has been built since ASP.NET MVC 3. Thanks
I think the best thing to do in your case is to create your own validation script. Its not hard, nor complex and you can address only the things necessary. So in my opinion just use js to hide, show and validate by your own script. (Just only validate the not hidden fields. )
If the fields are dynamic, doesnt mean you cannot have validation.
you can make validation dynamic, by breaking models down into smaller pieces and add validation to each smaller model.

MVC 4 Client Side Field validation for a list of fields (instead of fields as members of a class)

I am a long time backend .Net developer who is new to web application development. I am using MVC 4, Razor, EF 5, and I have a basic understanding on how to make a routine DB driven MVC 4 site with these tools.
I need to create a custom form capability for a workflow scenario. I have the entire code-first schema designed and classes for different formfield types, and formvalue type.
The model that will be passed to a view will be a form class with a list of formvalues, which contain form field specifications. So the view will have to iterate through the form fields and dynamically choose what editors to use and so on.
My problem is that this prevents me from using any data annotation for client side validation. And every place I find advice on custom validation assumes (not surprisingly) that all the fields are members of a class. Whereas, in this case, all the fields are on a list.
My goal is to end up with validation messages on each field and a validation summary as you would normally have if the view was simply bound to an annotated class.
Any suggestions on how to approach this? Thanks in advance.
Imagine view logic that has the following:
#foreach (var fieldvalue in Model.FormFieldValues) {
// Logic that chooses the appropriate editor based on typeof(fieldvalue.FormField)
// Binds the editor to fieldvalue.Value
// Validation specs are contained in the Formfield obtained by fieldValue.FormField
// And my problem is setting up the validation without the aid of the normal method
// of data annotation or class level custom validation.
}
and the fieldvalue class looks like this:
public class FormFieldValue : EboEntity
{
public string Value { get; set; }
[Required]
public int FormFieldId { get; set; }
[Required]
public virtual FormField FormField { get; set; }
[Required]
public int FormId { get; set; }
[Required]
public virtual Form Form { get; set; }
}
And imagine that the FormField object has fields such as Required, Maxlength, and so on, depending on the kind of field it is (i. e. FormFieldText would be a subclass of FormField)
ANSWER:
Ok, you can tell I am new at MVC.
The answer to my question is that the specific editors take htmlAttributes which can control validation. So in the case where one of my formfields is a required textfield of stringlenth(10), I can invoke the editor as follows:
<div class="editor-field">
#Html.TextBoxFor(model => model.NoTexty, new {
required = true,
maxlength = 10,
placeholder = "Texty"})
#Html.ValidationMessageFor(model => model.NoTexty)
</div>
but in my case the htmlAddtributes won't be hard coded, but rather they will come from the fields in the formvalue.FormField object.
Sorry if I wasted anyone's time on this. But I will leave this here for any other newbies like me.

What does it mean when a viewmodel contains [required]?

My project has viewmodels labeled like this:
public class locViewModel {
[Required]
public string City { get; set; }
}
If the view does not set a value then how can I detect this? Is this how the [required] works? Also what other kind of tags can I add to fields in a viewModel?
That means that for validation purposes you can do numerous things. For instance, in a View you can have client validation enabled and the form will not submit unless the control that is populating that property has data entered into it.
With a property with the Required attribute, and a Html.ValidationMessageFor(m => m.City, "City is required") you can notify the user on the client-side that it is a required field.
Here is a Great Resource on unobtrusive validation, and an in depth explanation of what you are looking for.

Ignore some fields using the helper #Html.EditorForModel()

I use helper #Html.EditorForModel() on all my views.
There is a desire that he skip two fields in my model, but only on this view, the other he must continue to display these fields as usual.
How can I skip these two fields only in this view?
Use the [ScaffoldColumn(false)] attribute.
E.g.
public class Person {
[ScaffoldColumn(false)]
public int PersonID { get; set; }
...
Solution and example sourced from: Pro ASP.NET MVC 3 Framework, Third Edition
I'd recommend writing viewmodels for any view that you want to deviate from default behaviour.
Side note: It's probably a good idea to write a viewmodel for every view, as you get separation of concerns, and it's easier to control the behaviour of each view.
Anyway...
For example, say your model is
class Herps {
public string Name { get; set; }
public int SecretToSomePeople { get; set; }
}
and you don't want to have SecretToSomePeople shown on one of your views, create a viewmodel that doesn't contain SecretToSomePeople
class Herps {
public string Name { get; set; }
}
and use that as the model for the desired view. Make sure you copy to/from the actual model somewhere though.
Strictly speaking, if you don't want to display the fields then they shouldn't be on the Model - the point of Models to to hold exactly the data required for the View.

Dynamic form with indeterminite number of items

I have a class:
class Item
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
I have a view where I want objects for the class above created using inputs (so I have a textbox for Name and a date select type thing for Date). However, I want thev user to be able to click a link and through jquery/javascript another textbox and date select will be added to the form, and this can happen unlimited times.
How can I bind this to a model so that I can return it to my action method? Ideally the model would be something like:
class MyModel
{
public string AProperty { get; set; }
public List<Item> Items { get; set; }
}
Apologies for the poor wording, struggling to describe what I want but I think this should get the point across.
You want to use a client-side template and then return JSON to your controller. If you are using MVC 3, JSON model binding is built-in, but in MVC 2 you need to set up your own binder. There is an example here.
I recommend using KnockoutJS for your client side. It's very simple for working with dynamic collections and very well documented. You can see an example similar to what you're trying to do here as well as in the previous link.

Resources