Last active
January 22, 2016 16:54
-
-
Save jimmason/6cb653e16f1ae5171106 to your computer and use it in GitHub Desktop.
View Model Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult(TestViewModel viewModel) | |
{ | |
//validate | |
if(!ModelState.IsValid) | |
return(viewModel); | |
//can also use addModelError where necessary | |
ModelState.AddModelError("","Some Other Error that i wanted to add"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class TestViewModel | |
{ | |
public string Email { get; set; } | |
public string Password { get; set; } | |
public string ConfirmPassword { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class TestViewModelValidator : Validator<TestViewModel> | |
{ | |
protected override void Rules() | |
{ | |
Ensure(x => x.Email.IsNotNullOrEmpty()).And(()=> | |
Ensure(x => x.Email.IsAValidEmailAddress())); | |
Ensure(x => x.Password.IsNotNullOrEmpty()).And(() => | |
Ensure(x => x.ConfirmPassword.IsEqualTo(x.Password))); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- View infomation can be added as overloads in the html helpers, this keeps view logic where it belongs --> | |
@html.LabelFor(model => model.Email,"My Email Address label") | |
@html.TexboxFor(model => model.Email) | |
@html.ValidationMessageFor(model => model.Email,"My Custom Error Message if i dont like the default") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment