Skip to content

Instantly share code, notes, and snippets.

@jimmason
Last active January 22, 2016 16:54
Show Gist options
  • Save jimmason/6cb653e16f1ae5171106 to your computer and use it in GitHub Desktop.
Save jimmason/6cb653e16f1ae5171106 to your computer and use it in GitHub Desktop.
View Model Validation
public class GivenAValidEmailAddressAndPassword : ViewModelValidationSpecification
{
private TestViewModel viewModel;
protected override void Given()
{
base.Given();
this.viewModel = new TestViewModel
{
Email = "foo@bar.com",
Password = "qwertyuiop"
};
}
protected override void When()
{
base.ValidateViewModel(viewModel);
}
[Then]
public void ThenTheModelShouldBeValid()
{
base.validationReport.Violations.Count().ShouldEqual(0);
}
}
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");
}
public sealed class TestViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
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)));
}
}
<!-- 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