I am using C#, MVC4 to build an account class that has a property called GmailAccount, which will be entered by the user.
In Model, I am using the following RegularExpression attribute:
[RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@gmail.com"]
This validates the email ends in @gmail.com
.
In my html view, I am simply using:
editorFor(model => model.GmailAccount) @@gmail.com
Note that I have typed in @@gmail in the html to save the user from typing in the domain name, and to ensure/enforce that user uses a valid gmail account.
However, we also note that the same RegularExpression attribute is validated on both the client and the server side. I really don't want my user to type in the domain name manually since I won't allow it to be different from "@gmail.com".
Question:
Is there a way to append @gmail.com to whatever the user provided in editorFor as the user name before both client side and server side validation? Or some other good alternatives?
What I would do is create a view model around what you are trying to do:
public EmailEntryViewModel
{
private string _emailPrefix = string.Empty;
public string FullEmailAddress
{
get
{
return _emailPrefix + "@gmail.com";
}
set
{
if (!value.EndsWith("@gmail.com", StringComparison.OrdinalIgnoreCase))
{
//whatever logic that is internal
throw new InvalidOperationException("Database contains an invalid email.");
}
this._emailPrefix = value.Substring(0,
email.IndexOf("@gmail.com", StringComparison.OrdinalIgnoreCase));
}
}
[RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"]
public string EmailPrefix
{
get
{
return _emailPrefix;
}
set
{
_emailPrefix = value;
}
}
}
Then you only need to:
@Html.EditorFor(model => model.EmailPrefix) @@gmail.com