Cybercop Cybercop - 1 year ago 94
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


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")]
[RegularExpression(@"^\(?([0-9]{10})", ErrorMessage = "*Not a valid number, must be 10 numbers")]
public string Phone { get; set; }

public DateTime DateTimeAdded { get; set; }
public string Comment { get; set; }



@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>


<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)
<label class="label">@Html.Label("Address")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Address)
<label class="label">@Html.Label("Phone")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Phone)
<div class="input-block-level">@Html.TextAreaFor(model=>model.Comment)</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" })

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 Source

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

@Html.ValidationMessageFor(model=>model.Address),"*Address is required",new { @class = "redclass" })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download