ASP.Net MVC Validation and Selenium Web Driver

Hackered
Tuesday, March 25, 2014
by Sean McAlinden

This is more of a reminder for myself, it is just a nice little bit of XPath for grabbing the built in ASP.Net MVC validation messages when using Selenium WebDriver.

So for this example, if you had a field called Title with a ValidationMessage in your Razor view such as:

@Html.LabelFor(x => x.Title)
@Html.TextBoxFor(x => x.Title, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Title)

You can use the following example in your Selenium Page Object to grab the validation message Span.

[FindsBy(How = How.XPath, Using = "//input[@id='Title']/following-sibling::span[@class='field-validation-error']//span")]
public IWebElement TitleValidationError { get; set; }

You can now grab the validation message via the IWebElement Text property.

var validationMessage = this.AddTitleValidationError.Text;

I'm pretty sure I will be copying and pasting this fairly often