views:

31

answers:

1

This question title is likely to be worded poorly so feel free to adjust.

In my MVC application I have a custom attribute which i use to decorate email fields which then either passes or fails the model.

On one pge though I allow the use to submit a comment but I submit via ajax and so do not do a full postback and no model validation.

So I'd like to validate the address but not copy the code. I'd also like to avoid breaking the code out of the validator into yet another class or is this the best wAY?

Is there another way? Can I create the model in the ajax postback and validate it there and then return the partial view with the error messages?

Or is there another way?

A: 

You say, ...

So I'd like to validate the address but not copy the code. I'd also like to avoid breaking the code out of the validator into yet another class or is this the best way?

IMO, that is the best way. Factor out the common code. I see your issue though, our EmailValidator inherits from RegularExpressionValidator, so it's hard to factor out. We have a RegEx utility class that uses the same RegEx pattern. We refer to the pattern by constant in both places...

public class EmailAttribute : RegularExpressionAttribute
{
  public EmailAttribute() :
    base(RegExUtility.SingleEmailAddressPattern)
  {
    ErrorMessage = "Please enter a valid email address";
  } 

and

public static class RegExUtility
{
  public const SingleEmailAddressPattern = @"...";

  public static bool IsValidSingleEmailAddress(string email)
  {
     return Regex.IsMatch(email, SingleEmailAddressPattern);

For simple Ajax postback actions, I think you can often handle it in the controller or create a separate POCO ViewModel that just supports the Ajax path. I know there are articles on using the same model for both types of actions, but we've found there are usually enough differences that it's worth having separate view models. If they're complex enough, we just factor out the common code.

Rob
Went with another solution in the end but this is still a correct reply me thinks. http://stackoverflow.com/questions/3472810/how-to-validate-a-model-in-a-jquery-postback
griegs