asp.net - How to create Custom Data Annotation Validators -


Want to create custom data annotation verification. Are there useful guides / samples about creating?

First of all:
string length with minimal and maximum length. I know. NET 4 can do this, but if this is possible, then being able to define the minimum length (at least x characters), the maximum length only (up to X characters), or both (between X and Y) In). Secondly: Validation using the modulus arithmetic: - If the number is a valid length, then I'm modulus 11 algorithm (I javascript, so I think it would be just a simple porting?)

Update:
The second problem solved, copying on javascript implementation and some tweaks, so it does not require a solution for it.

To create a custom data annotation verifier, follow these Gudelines:

  1. Your class to system ComponentModel.Data Annotation. The Legacy Attribute is inherited from the class.
  2. Apply override bool IsValid (object value) method and validation logic inside it.

That's it.

Important Caution

Sometimes the developers check that the value is not empty / empty and returns false. This is the wrong behavior usually , because it is a required validator to check that means your custom videographer should only validate the non-empty data, but True otherwise (see example). This will make them usable for compulsory (required) and non-compulsory areas.

example

  public class string string characterization: verification {public int min {get; Set; } Public Int Max {Received; Set; } Public String Langrange Attitude () {this.minimum = 0; this. Max = int.MaxValue; } Public override bool ISIIDID (object value) {string strValue = value string as; If (! String.isnaloractic (strue)) {int len ​​= strValue.Length; Return Lane & gt; = This. Minimum & amp; Amp; Lennon & lt; = This.Maximum; } Back true; }}  

All attributes can be set in attributes as you want them to be set.
Some examples:

  [required] [string lambandrends (minimum) = 10, error message = "must be" gtc: 10 characters. []] [String LelandRangeRange (max = 20)] [required] [String Lambendrej (minimum = 10, max = 20)]  

When a particular asset is not set, its The value is set in the constructor, so it is always a value I have intentionally added a required validator in the above mentioned examples, so I have written it with caution Is in sync.

Important

So this User will still work on your model value which is not necessary, but when it exists, it is valid (think of a text field in a web form, which is not necessary, but if a user enters the price Is to be valid).


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -