Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unobtrusive validation ignoring data-val attributes, but working with class="required"

I have the following view:

@using (Html.BeginForm())
{
    <div class="left-column">
        @Html.LabelFor(m => m.Expression)
        @Html.TextAreaFor(m => m.Expression, new { @spellcheck = "false" })
        @Html.EditorFor(m => m.Sku)
    </div>
}

With the following JavaScript which runs every second on a timer:

$("form").validate();

if ($("form").valid()) {
    //...
}

Generates the following html for the text area element (the only element needing validation):

<textarea 
    data-val="true"
    data-val-required="The Expression field is required."
    cols="20" rows="2"
    id="Expression" name="Expression"
    spellcheck="false">
</textarea>

The problem is that validation doesn't do anything, unless i manually add class="required" using browser tools. If i do this validation works and the error message "The Expression field is required" is displayed. To be precise "$("form").valid()" always returns true even when textarea is empty. Since i'm using anotations which automatically generate the data-val attributes, i'd like to rely on those. What am i doing wrong?

FYI my script refs look like this:

<script src="/Scripts/modernizr-2.0.6-development-only.js" ...
<script src="/Scripts/jquery-1.6.2.js" ...
<script src="/Scripts/Parser.js" ...
<script src="/Scripts/jquery.unobtrusive-ajax.js" ...
<script src="/Scripts/jquery.validate.js" ...
<script src="/Scripts/jquery.validate.unobtrusive.js" ...
like image 786
Luis Ferrao Avatar asked Nov 14 '22 00:11

Luis Ferrao


1 Answers

Have you enabled Unobtrusive Javascript and Client Validation for .NET?

Try setting the following in your view:

@{  Html.EnableUnobtrusiveJavaScript(true);
    Html.EnableClientValidation(true);
    Html.ValidationSummary(true);   
}

You can also set it sitewide in your web.config

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
like image 172
pantryfight Avatar answered Dec 10 '22 22:12

pantryfight