Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

view model validation that ignores leading and trailing spaces

Tags:

c#

asp.net-mvc

I have the following view model.

public UserViewModel {
 ...
 [Email(@"^.+@[^\.].*\.[a-z]{2,}$", false, ErrorMessage="...")]
 public string EmailAddress{ get; set; }
 ...
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Visitor(UserViewModel userViewModel)
...

However I have found that sometimes a user copies and pastes an email into the view from another email, word document etc and sometimes it picks up a leading and/or trailing space. As users are not the most intelligent and spaces do not show in the input control then really I should ignore these and carry on.

So if my model state is invalid, I am wondering the best approach to resolve this-

  1. Add spaces to my validation expression.
  2. In the action result method check if trim the email and remove the error from the modelstate manually.
  3. Do something else...

I am not 100% sure about 1, nor 2 too be honest!

like image 572
Rippo Avatar asked Nov 15 '11 13:11

Rippo


1 Answers

you can change the setters to have the trim code upon setting the value in the property too.

like image 65
Sumit Bisht Avatar answered Oct 23 '22 14:10

Sumit Bisht