I am having problems trying to invoke just one validator on it own, I know how to call on all validators to perform checks on buttons click events, by using Page.Validate() but how can I invoke lets say mySingledOutValidator I tried mySingledOutValidator.Validate() but that's not gonna work individual controls don't have .validate()
I need the following to be true:
Get a single validation to happen
In C# Asp.Net
.net 2.0 framework
If the above is not possible I do not mind looking into javascript alternatives.
If you can help it would be greatly appreciated.
You can use Group Validation. You can assign a validator a validationgroup value, and then explicitly validate that group, which can contain 1 or more validators.
Page.Validate("MyGroup");
You can also check the validation status of each validator explicitly using IsValid property, assuming validation has already taken place.
According this article:
function ValidatorValidate(val, validationGroup, event)
With jquery validators:
And in case I wanted to force the validation I should have written:
ValidatorValidate($("#<%= valEncOtherMimeTypeRequired.ClientID %>")[0]);
Related
I have to validate three things when a consumer of my API tries to do an update on a customer.
Prevent the customer to be updated if:
The first name or last name are blank
For a certain country, if the customer's inner collection of X is empty, then throw an exception. X is hard to explain, so just assume it's some collection. For all other countries, X doesn't apply / will always be empty. But if it's a certain country, then X is required. So it's almost a conditional required attribute. A customer belongs to a country, so it's figured out from the JSON being sent.
Prevent the customer from being updated if some conditions in the database are true.
So basically i'm stuck with the following problem, and I wanted some advice on the most appropriately way to solve it:
Do I create an Action Filter to do the validation on the customer entity before the saving takes place? Or would it be better to create custom validation attribute derived from ValidationAttribute and override the IsValid member function.
Basically a question of saying
if (first name is empty, if x, if y, etc) vs (!ModelState.IsValid)
And then using IsValid to cause the custom attributes to work.
It seems like validation attributes are best for "simple" validation, i.e. required field. But once you start getting into things like "I need to look at my database, or analyze the http request header for custom values, and based on that, invalid = false" then it almost seems wrong to do this sort of stuff so close to the entity.
Thoughts?
Thanks!
I like FluentValidation a lot: https://github.com/JeremySkinner/FluentValidation
As you mentioned built-in validation attributes are limited. For complex validations you had better implement your own attributes or use a library like this.
One thing I like about FluentValidation is that it performs at model-level rather than field-level, meaning that you can use related fields' values for validation. For example
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
(Code excerpt taken from project's Wiki page)
It's also extensible so you can develop your own custom validators on top of this library as well.
I am currently building a ASP.NET C# form. This form had many fields and many validations.
Which included:
Validate when the required checkbox is checked
Validate a dynamic form (e.g. additional address form generate dynamically when add address button click)
At first, I was planning to use ASP.NET form control to create all the fields and validations. But later on I found there is a plugin call jqueryvalidation, which simply provided what I need through Jquery.
Validate when the required checkbox is checked (http://jquery.bassistance.de/validate/demo/index.html)
Dynamic form (http://jquery.bassistance.de/validate/demo/dynamic-totals.html)
and my question is, if I am going to use this, would it be easier for me to create the form using standard HTML form tag instead of .NET control? Or can I still use .NET control?
I am quite struggle as I want to use the .NET control because I can obtain the value easily in code behind instead of Request.Form["fieldName"] but on the other hand, I feel not convenience to use the validation that .NET provided and I am not sure whether .net can create a dynamic form as easy as Jquery either.
Please advise. Thanks!
with validation plugin you can use "when required" case like this
$('#formSubmit').validate({
rules: {
ControlAspNetorSmtin: {
required: {
depends: function (element) {
if ($('#chkglobal').is(':checked')) {
return false;
} else {
return true;
}
}
}
}.... etc
If you are using ASP.NET MVC (which you probably should be) then your best bet would be to use auto-magic validation using model validation attributes and unobtrusive-validation. This would take care of client- and server-side validation with minimal effort (apart from defining the attributes).
I am working on a MVC 4 project. I am having an issue with multiple custom validation attribute on single property. Suppose I have 3 custom validation attribute for single property such as:
public class Test
{
[customAttribute1]
[customAttribute2]
[customAttribute3]
public string property1 { get; set; }
}
Currently when I post he form than all three custom validations are performed on the property (no matter whether first validation pass or fail).
What I want is if customAttribute1 validation fails than no need to validate the property with next next custom attribute. How can i achieve this?
The point of this behaviour is to return back (to the UI) all the errors in the Model, so the user can fix all the errors at the same time...
Let's say you want you password to be minimum 8 chars and have at least an uppercase and a number. The way you want your validation to run is to stop if the password is not long enough without checking the rest. Typical use case scenario:
User sets password "foo" -> submit
error - Password too short
User sets it to "foofoofoo"
error - Password must have an uppercase
User sets it to "FooFooFoo"
error - Password must have a number
User goes away frustrated...
So, if the 3 attributes are to be validated together, my suggestion is to keep this behaviour. If the 3 are exclusive then do as others suggested and combine them into a single attribute.
Ordering or executing conditionally is not supported AFAIK.
The best bet is to have all these 3 validations in the same attribute.
If you are badly in need of this kind of validation, then Fluent Validation can do it for you.
I'm new to C# MVC and I'm trying to add some dynamic validation checks to my view models that are used in a form. For example, I have a string property called FirstName. I can add the attribute StringLength(10) and Required() to it.
My problem is, depending on some other field, the FirstName StringLength could vary from 10 to 20, etc. I still want to use the MVC validations but be able to modify it. I know that attributes are bound to the class so maybe I'm using the wrong thing.
I want the abilities for attribute validation but have it modifiable at run time. Is this possible?
The values in an attribute have to be literals. You can still use attribute based validation, but you will need to use the CustomValidation tag and point it at a method to use. If it depends on multiple fields in the object, you will want to put this on the class rather than the property.
It seems you can add validation attributes at runtime by implementing DataAnnotationsModelValidatorProvider:
Dynamic Attributes # forums.asp.net
Is there away to add and remove DataAnnotations, in particular the [requried], from the code side of things? My problem is that I want to give the user the ability to save an incomplete form in our CRUD applications but at the same time use the power of the DataAnnotations validation.
If this is not possible, what is the best way I can go about this?
You can keep the DataAnnotation attributes on your model and then just manually clear the validation errors as needed from code. It might look something like this:
if (certainCondition == true) {
ModelState["someKey"].Errors.Clear();
ModelState["anotherKey"].Errors.Clear();
}
It is impossible to add, remove or modify DataAnnotations dynamically since they are Attributes. Attributes are part of the type and can't be changed during runtime.
You could use ModelState as Larsenal suggested provided that:
you use it After validation has executed. (prior to that, ModelState will be empty. It doesn't provide access to all validators, it only stores validator-errors after they've occurred)
you don't have any clientside validation that's based on the DataAnnotationValidators and fires errors that prevent you from even reaching the serverside validation.