In my ASP.NET MVC 4 application I am trying to use unobtrusive client validation with Fluent Validation.
<script src="/Scripts/jquery.validate.min.js" type="text/javascript">
</script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript">
</script>
I have these two .js files that VS2010 provides when new ASP.NET MVC 4 application is created. I have also enabled client side validation on my web.config file.
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As far as I know when client validation and unobtrusive JavaScript is enabled, input fields with a client-validation rule contain the data-val="true" attribute to trigger unobtrusive client validation. And I have these field on my input fields.
For instance,
<input class="input-validation-error" data-val="true" data-val-
required="error text here" id="purchasePrice"
name="PurchasePrice" type="text" value="">
<span class="field-validation-error error" data-valmsg-for="PurchasePrice"
data-valmsg-replace="true">'Purchase Price' must not be empty.</span>
However, when I submit my form, it is posted to controller and my model is checked on my controller code instead of client side.
EDIT :
This is my form opening tag.
@using (Html.BeginForm("Create", "Product", FormMethod.Post,
new { enctype = "multipart/form-data", @class = "mainForm",
@id = "productCreateForm" }))
Any ideas? Thanks.
Did you add the configuration for MVC?
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// this line is required for fluent validation
FluentValidationModelValidatorProvider.Configure();
}
You also need to configure each view model / validator:
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
If this does not help, could you post an example of a validator that is not working correctly? Not all validation can be done client side. For example, the following validator will only work server side:
// when validator rules are always server side
public class ServerSideValidator : AbstractValidator<Person> {
public ServerSideValidator() {
When(x => x.Name == "Foo", () => {
RuleFor(x => x.Email).EmailAddress();
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With