Cybercop Cybercop - 21 days ago 5
CSS Question

MVC4: On validation error, change the textbox color to red

I have a form which has some text boxes, and when the textbox doesn't contain valid value I get the error message but the textbox color doesn't change to red.

This is what I have

Model

public class AddCompany
{
public int Id { get; set; }

[Required(ErrorMessage = "*Name is required")]
public string Name { get; set; }

[Required(ErrorMessage = "*Address is required")]
[RegularExpression(@"^\(?([0-9]{4})\)?([A-Z]{2})",ErrorMessage = "*Not a valid Zip Code, Must be in format 1234AB")]
public string Address { get; set; }

[Required(ErrorMessage = "*Phone Number is required")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{10})", ErrorMessage = "*Not a valid number, must be 10 numbers")]
public string Phone { get; set; }

[DataType(DataType.DateTime)]
public DateTime DateTimeAdded { get; set; }
public string Comment { get; set; }

}


View

@model CrmTestProject.Models.ViewModels.AddCompany

@{
ViewBag.Title = "AddCompany";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>

<h2>AddCompany</h2>
@Html.ValidationSummary(true)

<fieldset class="form-horizontal">
<legend>New Company <small>Add</small></legend>
@using (Html.BeginForm("AddCompany", "Company"))
{
<div class ="controls">
<label class="label">@Html.Label("Name")</label>
<div class="input-block-label">@Html.EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model=>model.Name)
</div>
<br/>
<label class="label">@Html.Label("Address")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Address)
@Html.ValidationMessageFor(model=>model.Address)
</div>
<br/>
<label class="label">@Html.Label("Phone")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Phone)
@Html.ValidationMessageFor(model=>model.Phone)
</div>
<br/>
<div class="input-block-level">@Html.TextAreaFor(model=>model.Comment)</div>
</div>
<div class="form-actions" id="buttons">
<button type="submit" class="btn btn-primary" id="Submit">Save changes</button>
@Html.ActionLink("Cancel", "CompanyIndex", new { @class = "btn" })
</div>
}
</fieldset>


Browser ScreenShot
enter image description here

As you can see I get the error message but I also want the textbox and preferably error message color to be red. I don't know if it is due to bootstrap.
But when I check this blog for validation things work perfectly here.
Can anyone give me some suggestion?

Answer

Add a class in css and change its colour like this:

@Html.ValidationMessageFor(model=>model.Address),"*Address is required",new { @class = "redclass" })
Comments