I'm finding a lot of tutorials out there with tons to slog through, but for basic validations it doesn't have to be that complicated. Somewhere in your model (if you want), define a class for the attribute you'd like. The class will inherit from ValidationAttribute. It will have a method, public override bool IsValid, that takes an object as its argument. The object is what the field gives you. You can then define some logic in the method to get from that object to a truth value.
Below is a working attribute I cooked up to test whether an entry in a field (conceived as a decimal) is not zero. Note that the object has to be converted to decimal form before it can be tested (and an explicit cast doesn't seem like the way to go here).
Below is a working attribute I cooked up to test whether an entry in a field (conceived as a decimal) is not zero. Note that the object has to be converted to decimal form before it can be tested (and an explicit cast doesn't seem like the way to go here).
public class NotZero:ValidationAttribute
{
public override bool IsValid(object value)
{
var d = Convert.ToDecimal(value);
return d != 0;
}
}
So that's my bit. Don't read the long tutorials unless you need something fancy or have a pretty good understanding of how the validation stuff works. First try to copy and modify this. I can't guarantee it will work in every case, but it's a decent way to extend the basic annotations on the fly.
{
public override bool IsValid(object value)
{
var d = Convert.ToDecimal(value);
return d != 0;
}
}
Comments
Post a Comment