Validation of dynamic fields in a MVC - asp.net-mvc-3

My model looks like
public class Template
{
Id
Title
List<Field> Fields
}
The “Field” Entity contains information like Name, Caption, Type (TextBox/Select/Radio), Options, and validation rules (Range, Required, string length).
The standard validation in MVC is based on DataAnnotations, but I wants to validate (Both client and Server Side) the form dynamically based on Field Metadata which is dynamic and configurable.
Is it possible? Any pointers?
PS. I searched for the similar questions, but not able to find a solid answer.

I had a similar situation, this is how I handled it:
Server Side
When the POST happened I iterated over all the Fields values and did the Validation based on the validation rules I had on my objects. Then you can simply add ModelErrors to the Field object.
Since you push a Template object to the View you can access the Fields by name Fields[x].SomeProperty. Make sure you have a ValidationMessageFor for SomeProperty
ModelState.AddModelError("Fields[x].SomeProperty", "The Error Message you want to show.);
Client side
Make sure your form has an Id so you can access the Validate method().
Then you iterate over all the fields and just add the validation as you please.
For all the validations rules check the validation Jquery documentation.
$('#frmYourForm').validate();
for (var i = 0; i < 'CountOfAllFields'; i++)
{
$('#Fields_' + i + '__Foo').rules('add', { required: true, messages: { required: 'The Foo field is required'} });
$('#Fields_' + i + '__Bar').rules('add', { required: true, messages: { required: 'The Bar field is required'} });
}
I hope I helped you on your way !
Ps, use FireBug to help you find the correct names of the properties and that's how you can link them with the ModelErrors in the modelstate etc.

Related

Can I dump a Symfony form's validation schema to JSON?

I'm considering setting up some proof-of-concept tool that could grab metadata from a Symfony2 FormType instance in order to dump a validation schema as JSON, something like the following:
[
{
name: 'someFieldName',
value: '',
email: true
},
{
name: 'yetAnotherFieldName',
value: 'I have a default value',
required: true
}
]
The aim obviously is to use it in front-end JS code (let's say React), to be able to set up the same validation constraints, as much as possible (required and the likes).
However, Symfony is well-architectured and its Form component knows nothing about validation. Considering only the nominal case of a simple form to begin with, how would one go about doing it? How to map back the form to the validatable objects/entities it references?
Using the symfony validator you can get the metadata for a given class:
$this->get('validator')->getMetadataFor(Foo::class);
It returns a ClassMetadata instance. If the passed value is an entity, you will have the members and properties properties returned which then contain a constraints property with the classes being used.
Final step is to serialize that in JSON.

Spring MVC and annotations, how to do a validator in the case of a form that will contain different fields depending of a combo box

I am trying to accomplish the following:
I have a form that starts with a combo box, let's say that the user will have to pick either "Student" or "Teacher".
Both "Student" and "Teacher" will have the same fields displayed in the form, but if "Teacher" is checked, I will have more fields being displayed (that are hidden at first and that I will show with jQuery when the user select "Teacher").
The problem is that I want those fields to be mandatory only if "Teacher" is selected.
I have no idea to manage that, I don't think it's gonna be possible using annotations such as:
#NotBlank
private String teacherCourse;
since this field will always be blank when the user will have selected the "Student" radio button.
Any idea? Can I do a custom validation method and how?
I've taken two approaches with this in the past.
Use an enum field on the submission to determine which type of validation to perform. This is flexible and allows for any number of custom validation methods.
An alternative is to use a base command object which both student and teacher classes extend. This allows both types to extend and override validation and fields. This requires that separate methods are used to bind each type.
You could use validation groups to differentiate between constraints applying to both entities and those applying to only one of them:
public interface TeacherConstraints {}
#NotBlank(groups=TeacherConstraints.class)
private String teacherCourse;
When validating your object, specify the group to validate depending on the type selected in your combo box:
//teacher
Set<ConstraintViolation<Object>> violations = validator.validate(object, TeacherConstraints.class);
//student
Set<ConstraintViolation<Object>> violations = validator.validate(object, Default.class);
You can use javascript or JQuery for front side validation... depending upon your combo box value. If it's a teacher or student
function validate(){
var combox_value = document.getElementbyID("combo_box").value;
if(combox_value == "Teacher"){
//Validate for Teacher fields
var input_text1 = document.getElementbyID("input_text"2).value;
if(input_text1=="" || input_text1==null){
alert("Field cannot be empty");
return false;
}
return true;
}
else if(combox_value == "Student"){
//Validate for Student fields
var input_text2 = document.getElementbyID("input_text2").value;
if(input_text2=="" || input_text2==null){
alert("Field cannot be empty");
return false;
}
return true;
}
}
For JQuery try these links for live examples...
http://speckyboy.com/2009/12/17/10-useful-jquery-form-validation-techniques-and-tutorials-2/
http://www.jeasyui.com/tutorial/form/form3.php
http://www.camcloud.com/blog/jquery-form-validation-tutorial

Validate Custom Sharepoint field if Empty?

I'm using Sharepoint 2010 .. with a custom field in visual studio 2010.
I created a custom field. This particular one is a datetime field ("Termination Date"). I want it to fail validation if it is blank and another field ( "Contract Terminates" is equal to yes ).
So I had previously did this with a calculated field. And that works but it puts the validation error at the top of the edit form, not next to the "Termination Date" field where I want it.. like it would normally be if the field failed validation using GetValidatedString in a custom field.
So because it's in the wrong place, I made a custom field. But because the date is blank, it never hits GetValidatedString method. Am I missing something? is there another way to have it fail validation and be next to the 'Termination Date' field if the 'Termination Date' field is blank?
I'm tried using an event receiver solution also.. the problem there is that it would also put the error message on the top.. not next to the Termination Date field.
Suggestions?
For custom field you could override FieldRenderingControl, write your own FieldControl. If you don't use this custom field in Whereabouts list you could inherited your fieldcontrol from DateTimeField and override Validate method e.g:
public override void Validate()
{
base.Validate();
if (IsValid)
{
if (!(your validation))
{
IsValid = false;
ErrorMessage = “youe message”;
}
}
}

How do you validate only if there's input?

Using Asp.Net MVC3, I have many steps in a wizard where after every step I do a $.post to capture what was entered. The first two steps are simple and all fields are required no matter what.
The rest of the steps are not required. However, if step 3 has 10 input fields and entered values for 5 out of 10, then validations have to kick in (just for the 5 fields and display the errors for those 5 only). So in essense, things like [Required], [StringLength] and [RegEx] should kick in only if someone actually entered anything for those 5 fields. If nothing is entered, validations should be skipped.
I was thinking of naming or prefixing each step (div) with Required or Optional as
Hope there is an answer.
If you divide each step on your wizard into a separate form, then validation can be performed when necessary on that step's form.
Please be aware that BY DEFAULT StringLength and RegEx attributes will only be validated when information is entered in that particular field. If the fields are blank, validation of those attributes will not occur.
As far as Required attributes, I am unclear what you are asking. Are you saying that there are fields in a particular step which will be required based on a condition in another field? If so, then you must implement a conditionally required validator.
You can make your viewmodel implement IValidatableObject. The interface requires one function, IEnumerable<ValidationResult> Validate(ValidationContext validationContext). MVC will validate the model first from any DataAnnotations, then on the Validate function on the model (so twice, which isn't always what you want).
For example,
public class Input : IValidatableObject
{
public string Name { get; set; }
// ... Other fields ...
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (String.IsNullOrEmpty(Name))
{
// ... Validation rules ...
results.Add(new ValidationResult("Please enter a name.", new[] { "Name" }));
}
return results;
}
}
More information from Scott Guthrie's blog.
You could write custom a validation attribute and perform this validation logic in the IsValid method where you have access to the value and could check whether the value is not null or empty and only then proceed with the default validation.

jqGrid saving a row with nullable columns

So I have a jqGrid on an ASP.NET MVC 3 website. It's loading the data, searching, filtering, and saving rows with the built in pop-up editor. What I can't get to work is saving a nullable property. I'm using LargeJsonResult instead of the built in JsonResult, so an example of a row in the grid is this:
// C# class
public class Row
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
}
// an example object instance, let's say these values come from the DB
var ret = new Row { A = "a", B = null, C = 5 };
// the JSON string sent to the grid will look like this (notice B is omitted)
// "{ A: 'a', C: 5 }"
Now, the grid will show this as:
A B C
a undefined 5
And this brings me to my problem. The pop-up edit form will show "undefined" in the textbox for B, and will also post this to the server. So if I save that to the database, I'll have "undefined" in my DB instead of null.
How do I get jqGrid to preserve the null value round trip? One solution that seems to me very hacky is based on something Oleg solved in another thread:
// override jqGrid serialization
jQuery.extend(jQuery.jgrid.edit, { ajaxEditOptions: { contentType: "application/json" }, serializeEditData: function (data) {
return JSON.stringify(data).replace(/"undefined"/g, 'null');
}});
This will work, but seems dangerous because it's doing mass edits of data without the user's knowledge. In thinking more about it, I guess this is the fundamental problem of saving back null instead of "undefined" or some other string representation of null (empty string, etc.). The desired behavior would be:
if the property is null, and the user doesn't change the value, it posts as null
if the user changes the value, the property is no longer null
Can we get the grid's edit form to behave like this for nullable properties? Or would I have to create a custom edit form that tracks what the user does with a property?
I hope that I understand your problem. In one my applications where I used jqGrid I had once the problem with NULL values. At the time of development of the application I was not sure how to solve the problem and I placed on the server side the text value "(NULL)" instead of null value of one property. The grid was for advanced users who understand what "(NULL)" is. The value "(NULL)" has no sense in the field (one had no user account with the name) and inside of server code for the Edit operation I could distinguish "(NULL)" value from the real field value. In the way I could come over the problem.
In your case you should solve at least two problems:
You should decide how the null value should be displayed. The "undefined" text seems me not the best one. You can solve the problem with the "undefined" text either on the server side (like I did in my case) or with respect of custom formatter. The custom formatter is very simple thing. It define how a cell value should be displayed as a HTML fragment of the <td> contain. You can for example include an additional hidden <span> element or other HTML element or attribute which will save the information that the value was null.
You should solve the problem with decoding of the null value on the server side during Edit operations. You can solve the problem very easy on the server side (like I do with compare of the corresponding field to the "(NULL)") or with respect of custom unformatter on the client side. The custom unformatter will get the information from the grid cell (from the hidden <span> or other hidden HTML element or attribute) and place the information in the server request.
You can look at the demo for the answer to see an example how one can use a hidden <span> to save an additional information in the cell with respect of custom formatter and to read the information later with respect of custom unformatter.

Resources