Khelvaster
Khelvaster

Reputation: 872

Client-side validation not working from data annotations; server-side does

I'm having trouble getting client validation to work on a web form. I'm including .js files and have the relevant lines in web.config, but data validation doesn't get put into the HTML on the client side.

My layout, which is being applied to the page, looks like

<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript" ></     script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript" ></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
</head>

My web.config file has the following:

<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="false" />
</appSettings>

My page's viewmodel has proper annotations and is being validated properly on the server-side

[DisplayName("Url")]
[DataType(DataType.Url, ErrorMessage = "Invalid Url")]
[StringLength(30)]
[Required]
public string url { get; set; }

[DisplayName("Email")]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
[Required]
public string email { get; set; }

Finally, I am including the following HTML in my page:

<div class="conLine">
@Html.LabelFor(m=> m.url):  @Html.TextBoxFor(m => m.url) 
@Html.ValidationMessageFor(m => m.url)
</div>
<div class="conLine">
@Html.LabelFor(m=> m.email):  @Html.TextBoxFor(m => m.email) 
@Html.ValidationMessageFor(m => m.email)
</div>

The HTML output by the page at this section looks like:

<div class="conLine">
<label for="url">Url</label>
: 
<input class="input-validation-error" id="url" name="url" type="text" value=""/>
<span class="field-validation-error">The Url field is required.</span>
</div>

I'm about at my wit's end with this. Any help would be greatly appreciated!

Upvotes: 0

Views: 1646

Answers (1)

dohaivu
dohaivu

Reputation: 2027

You should wrap these code in Html.BeginForm

@using (Html.BeginForm()) {
    <div class="conLine">
    @Html.LabelFor(m=> m.url):  @Html.TextBoxFor(m => m.url) 
    @Html.ValidationMessageFor(m => m.url)
    </div>
    <div class="conLine">
    @Html.LabelFor(m=> m.email):  @Html.TextBoxFor(m => m.email) 
    @Html.ValidationMessageFor(m => m.email)
    </div>
}

Upvotes: 3

Related Questions