开发者

Datatype attribure implementation

In my property i need a email address validation. But [Datat开发者_StackOverflowype(DataType.EmailAddress)] was not working. How to rectify the same.


While you aren't being too clear on where you need to perform the validation, but assuming you had a class like this:

public class MyClass
{
    [DataType(DataType.EmailAddress)]
    public string EmailAddress { get; set; }
}

The validation of the EmailAddress property does not occur on the setting of the property.

However, you can trigger the validation by using the methods on the Validator class:

// The instance.
var myClass = new MyClass { EmailAddress = "someone@somewhere.com", };

// The context for validation.
var context = new ValidationContext(myClass, null, null);

// Validates the property.
Validator.ValidateValue(myClass.EmailAddress, context, 
    new ValidationAttribute[] { new DataTypeAttribute(DataType.EmailAddress), });

Of course, that defeats the purpose of declaring the attribute on the class declaration. You can validate the entire class state like so:

// Using same myClass and context declarations:
Validator.ValidateObject(myClass, context);

If you prefer to not to try/catch Exception instances, then you can use the Try* versions of the Validate methods instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜