I figure this must be so simple and I'm missing something really obvious. I want to validate the selected value of a select input on an ASP.NET Web Pages 2 form using the built in validators but it doesn't look possible so far.
For example:
Validation.Add("my-select", Validator.ValueEquals("Some Value"));
Where Validator.ValueEquals would compare the selected value to the supplied parameter value "Some Value". I realize I could do:
if(Request["my-select"] != "Some Value") {
Validation.AddFormError("Invalid option selected");
}
But then I don't have the error message associated with the field and it will only appear if I'm rendering the validation summary at the top of the form.
What am I missing?
I've cracked the code! Unfortunately the solution is outside of the scope of the built in Validation and Validators static methods but I was able to achieve what I needed by using the following in place of the using the Validation class.
if(Request["my-select"] != "Some Value") {
ModelState.AddError("my-select", "Invalid option selected");
}
Then check if the ModelState is valid when checking Validation.IsValid():
if(ModelState.IsValid && Validation.IsValid()) {
// More codes...
}
It's kind of cool that ModelState is available but it really seems clunky that this isn't handled by the Validation and Validator classes.
You could use the EqualsTo validator and compare the supplied value to a hidden field value, or if you are worried that users might tamper with the hidden field value, you can write your own custom validator. I've blogged how to do that: http://www.mikesdotnetting.com/Article/195/ASP.NET-Web-Pages-Creating-Custom-Validators
Related
I have a quick form like so:
{{> quickForm schema=competitorSchema id="newCompetitorForm" type="method" buttonContent="Save Competitor" meteormethod="insertCompetitor" tid=tournament._id }}
This is in a modal popup BTW.
Now in the method code I had a defect and did not specify one of the required fields in the mongo insert operation so what happened was:
Client side validation passed (cause I had populated all the required field in the form)
When the actual insert occurred collection2 threw the proper error saying field X was missing.
This was thrown back to me and I catch this in my onError: auto form hook like so:
onError: function(operation, error, template) {
if(error){
alert(error);
}
}
This could any general error - for any reason BTW.
Alert is not what I want to use here... cause it's not very nice. Collection2 throws "Error: X is required" but I don't really want to parse out the string field name since that's sorta brittle trying to match that with a form key since it seems like X is actually the label.
I can come up with a bunch of work arounds like populating a special div or popping a modal etc but what I really want is for auto form to handle this for me with a generic form level validation error (not a specific key).
Does anyone know if there a nice way built into auto form to display a form level (not field specific error) to the user? I did not see this in the docs.
I see how I can use addInvalidKeys etc for a specific field but what I want to do is use something like addInvalidKeys with no key so it displays a form level error message etc.
You can return whatever you want from the method call return function, so you can return human readable messages as a string or object.
If Alert doesn't work for you, you can use a Modal to put up a nice message.
It's really not much code.
You can populate a Session variable when there is an error and add a banner div of some sort.
If you want VALIDATION, then use a SimpleSchema with your autoform and it will work automatically, but that only validates the input matches the Schema, not backend insertion errors etc...
I am using asp.net MVC3 and I am very new to this technology.
My models are designed in such a way that the properties will throw validation errors if the data is invalid. In this case, the properties are not set with invalid data.
When I redisplay my editing-view, validation error messages are shown; however the values that the user previously entered are gone because the model that it is bound to only contains the old-valid data.
For example, say I had a Person class and the Name property cannot be a null or empty string otherwise it throws a validation exception and prevents the property from being set. Now say the user removes the value from the Name property and tries to save the Person from the web. A validation exception will be thrown and handled properly to add the error to the ModelState so that it is displayed on the screen; however the old value for the Name is redisplayed since the invalid, empty string never made it into the property.
I do not know how to solve this problem and any advice on the issue would be greatly appreciated.
My advise is allow invalid data but use validation attributes. You wont save invalid entities so there is no problem and this is the standard approach these days. If you don't want do that, there is no easy solution. Most simple solution would be using the info from Request.Form
You should implement IValidatableObject to performe this kind of validation at server side.
From MSDN IValidatableObject Interface:
Provides a way for an object to be invalidated.
Theres an exemple here Using IValidatableObject Custom Validation, also from MSDN.
The solution to this problem was to create a ViewModel that allowed invalid data to be entered into this. This solution also simplified my ModelBinder classes because it took on most of the work.
I wish to use the same form for adding and editing records within a database using a partial view. I understand that this is fine as the standard Html.BeginForm automatically output the correct html depending on the action that is being used (Add / Edit).
However, I need to out said form with some extra HTML attributes. There does not appear to be an overload that allows this to happen without also specifying the ACTION and CONTROLLER names.
If I hardcode these then surely I cant use the same form for edit and add automatically?
Or am I missing something?
CHeers
Set the values of the action and controller to null and they will be pulled from the context. If you look at the source for the overload that doesn't require parameters, you'll see that it simply calls the versions requiring more parameters with these values as null. Calling that overload directly with null values will have the same effect. Depending on the overload you're using you might need to cast the null values as strings -- I'd do this only if the compiler is not able to differentiate the methods without casting the nulls as strings.
<% using (Html.BeginForm( null, null, FormMethod.Post, new { #class = "foo" } ))
{ %>
<% } % >
Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox. I would like to validate that the user checked the box. The [Required] attribute on my ViewModel doesn't seem to do the trick. I believe this is because the unchecked checkbox form field is not actually transmitted back during the POST, and therefore the validation doesn't run on it.
Is there a standard way to handle checkbox "required" validation in MVC2? or do I have to write a custom validator for it? I suspect the custom validator won't get executed either for the reason mentioned above. Am I stuck checking for it explicitly in my controller? That seems messy...
Any guidance would be appreciated.
Scott
EDIT FOR CLARITY: As pointed out in comments below, this is a "agree to our terms" type of checkbox, and therefore "not checked" is a valid answer, so I'm really looking for an "is checked" validation.
a custom validator is the way to go. I'll post my code which I used to validate that the user accepts the terms ...
public class BooleanRequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
I usually use:
[RegularExpression("true")]
If you didn't want to create your own custom validator and still wanted to use existing attributes in the model you could use:
[Range(typeof(bool), "true", "true", ErrorMessage="You must accept the terms and conditions.")]
This ensures that the range of the boolean value is between true and true. However, whilst this method will work, I would still prefer to use a custom validator in this scenario. I just thought i'd mention this as an alternative option.
I too am looking for a way to have the model binder correctly handle check boxes with Boolean values. In the mean time I'm using this in the Actions:
Object.Property = !String.IsNullOrEmpty(Request.Form["NAME"]);
Maybe this will be of some use to you.
I'm building an ASP.NET MVC application with a form that needs validation. The majority of the form is static, but part of the form is dynamic.
I need to enable the user to enter n string/date combinations.
The string/date combos need to be validated server side, and I need to give feedback to the user preferably directly beside the combination that failed validation.
For static input I do the following:
<%= Html.ValidationMessage("someField") %>
For the dynamic data, what should I do?
In your controller you'll want to assign an error to the particular fields that fail validation:
ModelState.AddModelError ("textbox1", "You must specify a valid string.");
ModelState.AddModelError ("combobox1", "You must specify a valid date.");
Then all the helper is really doing is checking if the following exists:
ViewData.ModelState.ContainsKey("textbox1")
and then creating a tag such as follows
<span><%= ViewData.ModelState.ContainsKey("textbox1").Errors[0] %></span>
the helper does a bit more null value checking but you get the idea.