Validate Custom Sharepoint field if Empty? - validation

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”;
}
}
}

Related

Play Framework: automatic validation of controller methods applied?

I have some issue with validation of parameters passed to a controller method.
Following the suggestion from the tutorial, I am using the same controller method for "save" and "create new" of an entity. See example in
http://www.playframework.org/documentation/1.2.4/guide9
So, my controller method looks like:
public static void saveEntity(long l, Long itemId,
#Required(message="error.shouldspecifyname") String name,
#Required(message="error.shouldspecifycategory") String category)
If 'itemId' is not part of the data sent via an HTTP request - it is supposed to be set to 'null'.
Unfortunately, it seems like "Play" is automatically adding a validation error on the "missing" parameter.
When looking into the validation errors' list, every time 'itemId' is 'null' - I am getting an error Incorrect value for field itemId
Is it a documented behavior? Any way to override it, or "get rid" of the error.
I am handling the errors simply using redirection, like:
if(validation.hasErrors() )
{
validation.keep();
showSomePage();
}
So the errors are displayed "out of the context" they get generated. This is the reason the "automatic" error bothers me.
Thanks for any hint.
Most likely it fails to validate itemId because it's declared as Long, are you sure you have "Long" there ant not just "long"? We are using validation with controllers every where and it works with #Required and passed "null" to "Long" values.
Worst case you can remove error from validation object based on "itemId" key, also if you're using controller to save model object, you might want to use:
public static void saveEntity(#Required #Valid MyEntity entity) {
if(validation.hasErrors() ) {
validation.keep();
showSomePage();
}
entity.save();
}
It will automaticly hook your changes inside existing entity if you pass ID from page with:
<input type="hidden" name="myEntity.id" value="${myEntity.id}">

Validation of dynamic fields in a MVC

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.

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.

.NET MVC3 Remove Currency Symbol and Commas

In my model I have the following property:
[DataType(DataType.Currency)]
public decimal? Budget { get; set; }
When the user enters in $1,200.34, I need that value to be valid and strip out the currency symbol and comma.
In my controller I'm doing:
if (race.Budget != null)
{
race.Budget.ToString().Replace("$", "").Replace(",", "");
}
The problem is that client validation doesn't pass the value for budget into the controller. I get a value of null. How can I override the client validation so that I can strip out the currency symbol and comma?
Thank you in advance for the help.
UPDATE
So here's the strange thing. Let's say I want to bypass client validation all together. I added #{ Html.EnableClientValidation(false); } to my view and it's still sending a null value for Budget when I submit to the controller.
This isn't a client side validation problem. Your model has a field of type decimal? The model binder will try to bind a value of $123,456.78 into that and fail, so the value will be null. Here's one way to get around this:
Change your model to have a string property that masks your decimal:
public decimal? Budget { get; set; }
public string BudgetText {
get {
return Budget.HasValue ? Budget.ToString("$") : string.Empty;
}
set {
// parse "value" and try to put it into Budget
}
}
Then, just bind to BudgetText from your View. Validate it as a string with a regular expression that accepts only money input. It'll probably be the same regex you can use for your BudgetText's set method
So you can probably hook in some JQuery to pre-process the form field to strip the characters off you don't want (prior to form submission to the server). This is probably the quickest, dirtiest approach.
For something reusable, have a look into custom client validation adapters. The links aren't spot on, but should get you in the right direction. For Brad's screencast, I believe the relevant parts are fairly early on.
Check out the support for jQuery localization
cliente validation using jQuery validate for currency fields
also there is a plugin for currency validation as well
http://code.google.com/p/jquery-formatcurrency/
check out this recent post as well for a $ in binding
.NET MVC 3 Custom Decimal? Model Binder

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