3

I am using remote validation to make sure that the email and username fields in a user class stop a user from entering a username and/or email that already exists within the database.

This works fine on the create view, however the obvious problem I run into in the edit view is that when I try save some changes for a given user - I get the same validation messages on the username and email saying that they already exist in the database! Therefore stopping me from editing anyone because their emails and usernames already exist.

I have been looking around and was surprised that I could not find a similar problem to mine. I have seen many examples of dupliate name/email/value validation on create pages but nothing on the inevitable problem that will arise in the Edit view.

Any hints/tips on a way around this would be greatly appreciated. Maybe there is a way to make the validation only work in the create view? Though ideally, I want the validation in the edit view, just excluding the user's own name and email in the validation checks.

Thanks in advance for any answers!

DevDave
  • 6,700
  • 12
  • 65
  • 99

2 Answers2

3

You should use view models. Those are classes which are specifically designed to meet the requirements of a view. Controller actions should take/pass only view models to views and never your domain models. So you will have two controller actions, one for inserting and one for editing, and two corresponding view models with their respective validation rules.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I don't think that's related to what he's asking. – Jeremy Holovacs Aug 16 '11 at 12:22
  • oops, entered the comment when I pressed enter! The view models allowed me to separate what happened in the different views and then I was able to exclude the orignal email in the edit view whilst still validating against other emails. thanks again – DevDave Aug 16 '11 at 14:26
1

The way I've gotten around the problem is having 2 different validation methods; one takes a single argument (the user name) and one takes 2 arguments (the new user name, the original user name). The Edit method validates against the 2 argument method, where it looks for the new user name unless it matches the original user name.

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254