Multiple validations on a property using FluentValidation
I'm using FluentValidation and ASP.NET MVC 3.
I just have a couple of questions regarding the validation.
I have my validation on my view model setup like this:
public NewsViewModelValidator()
{
// Title is required
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required");
// Title must be less than or equal to 100 characters
RuleFor(x => x.Title)
.Length(1, 100)
.WithMessage("Title must be less than or equal to 100 characters");
}
Is this how it must be done, or do I need to include it in 1 statement?
I need 2 validations to be done on the Title property, name that it must be a required field and that it cannot be longer than a 100 characters. Below is the source after validation is triggered:
<td valign="top"><b>Title: *</b></td>
<td>
<input class="input-validation-error" data-val="true" data-val-length="Title must be less than or equal to 100 characters" data-val-length-max="100" data-val-length-min="1" data-val-required="Title is required" id="Title" max="100" name="Title" size="100" type="text" value="" /><br>
<span class="field-validation-error" data-valmsg-for="Title" data-valmsg-replace="true">Title is required</span>
</td>
It's using 2 different classes, one for each validation type. Why is this? Now my form is not consistent. I have another input field that is required, and the class that is used for this is input-validation-error, above it was field-validation-开发者_StackOverflow社区error.
How do I enable client-side validation? I was told that if I have the following code set in my web.config then client side is automatically turned on:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
Client-side validation is not triggered. Do I need to include the jQuery library or is this done for me?
You need to add these to your _Layout.cshtml :
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
精彩评论