Paul
Paul

Reputation: 12799

Exclude a property from unobstrusive client Validation with MVC 3

I have a class User, that have an Email property, like that :

public class User : Entity
{       
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}

My View Create works fine with all the validation ... But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks

Upvotes: 0

Views: 778

Answers (3)

Joe Cartano
Joe Cartano

Reputation: 3037

You could use different ViewModels for the edit and create views and only apply the Remote attribute to view model associated with the create view or call some other remote validation logic for the view model associated with the edit view.

Upvotes: 0

Jokin
Jokin

Reputation: 4218

I think that the easier way is to disable the field in the client instead of using readonly. The validate plugin doesn't take in account disabled fields.

Upvotes: 1

archil
archil

Reputation: 39501

Best solution would be to render Email as text content(span, p, etc) in that particular case - validations would not fire. This would be best accomplished with editor templates. But if you don't wish to, you could use some javascript to remove rules on client side. Take a look at Plugins/Validation/rules - you would remove rule when textbox is readonly. But for me the first way is preferred option

Upvotes: 1

Related Questions