Remote Validation in ASP.NET MVC 3 - asp.net-mvc

I am trying to get remote validation working in ASP.NET MVC 3 but for some reason the validation never gets fired. I am returning json from the controller and in FireFox it ask me to download the files. Not sure what is going on here. Here is my code:
#using(Html.BeginForm(new {Action = "ValidateUserName"})) {
<text> Enter UserName: </text> #Html.TextBoxFor(x => x.UserName)
<input type="submit" value="Login" />
}
Here is the RegistrationViewModel:
public class RegistrationViewModel
{
[Required(ErrorMessage = "UserName is required!")]
[Remote("ValidateUserName","Home",ErrorMessage ="UserName already taken!")]
public string UserName { get; set; }
}
And here is the HomeController:
public ActionResult ValidateUserName(RegistrationViewModel registrationViewModel)
{
return Json(!registrationViewModel.UserName.Equals("test"),JsonRequestBehavior.AllowGet);
}

A couple of things to consider:
1) In your view, you should be referencing the jquery validation and unobtrusive javascript libraries:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
2) Also in your view, you should have an Html.ValidationMessageFor(m => m.Attribute):
#Html.ValidationMessageFor(x => x.UserName)
3) Lastly, make sure you have the two AppSettings in your web.config file that enable the client-side validation.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

Related

Remote validation isn't working in mvc.

I am using remote validator but it's not working even debugger isn't tracing that method.
public JsonResult CheckStrategyName(string StrategyName)
{
var ab = from a in db.Sterategy where a.StrategyName == StrategyName select a.StrategyName;
return !ab.Any() ? Json(true, JsonRequestBehavior.AllowGet) : Json(string.Format("Name Already esists"), JsonRequestBehavior.AllowGet);
}
I have used it here
[Required]
[Remote("CheckStrategyName", "St", ErrorMessage = "Already exists ")]
[Display(Name = "Name")]
public string StrategyName { get; set; }
Webconfig
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Where am I making mistake ? :(
Your server code & settings seems to be fine. Make sure the following are in place
You are using the TextBoxFor helper method to generate the relevant input field markup and it is inside a form.
#using (Html.BeginForm())
{
#Html.TextBoxFor(s => s.StrategyName)
#Html.ValidationMessageFor(s => s.StrategyName)
<input type="submit" value="Submit" />
}
You have included the javascript libraries needed for validation.
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

ASP.NET MVC Unobtrusive client validation not working

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();
});
}
}

Client side validation randomly not working

I'm trying to validate this model:
public class LogonModel
{
[Required(ErrorMessage="Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
}
In this action:
public ActionResult Logon()
{
LogonModel model = new LogonModel();
return View(model);
}
In this View:
#model POCModelValidation.Models.LogonModel
#{
ViewBag.Title = "Index";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<h2>Index</h2>
#using (Html.BeginForm())
{
<h3>username</h3>
#Html.EditorFor(model => model.Username)
<h3>#Html.ValidationMessageFor(model => model.Username)</h3>
<br />
<h3>Password</h3>
#Html.EditorFor(model => model.Password)
<h3>#Html.ValidationMessageFor(model => model.Password)</h3>
<br />
<h3>Email</h3>
#Html.EditorFor(model => model.Email)
<h3>#Html.ValidationMessageFor(model => model.Email)</h3>
<input type="submit" value="Submit"/>
}
..And I can't figure out the pattern in which it works, but it never works for the whole 3 fields. Other than that, if I fill, leave, then go back and delete the content of the fields enough times, it eventually works for all of them, but rarely on the first time, and never for all of them at the same time.
I do have these line in my web.config
...
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
...
And in _Layout:
...
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
...
Any ideas?
Load up Fiddler http://www.fiddler2.com/fiddler2/ and ensure the scripts are properly getting loaded. If they aren't, validation just won't work.
Please add the following line to your code
<%Html.EnableClientValidation();%>
#using (Html.BeginForm())
**Your code**

Custom DateTime validation in ASP .NET - MVC

I try to implement new validationrules in my MVC-Project but i wont become a validation-errormsg in my view.
What is wrong with the code? I have googlet alot and thought i have done all right -.-
WebConfig:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
Model:
public class Model1 : IValidatableObject
{
[Required]
[DisplayFormat(DataFormatString="{d:0}", ApplyFormatInEditMode=true)]
public DateTime Wunschtermin { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Wunschtermin < DateTime.Now) yield return new ValidationResult("error1!", new[] { "Wunschtermin" });
if (Wunschtermin.Date > DateTime.Today.AddYears(2)) yield return new ValidationResult("error2", new[] { "Wunschtermin" });
}
...
View:
#model TestMvcApplication.Models.Model1
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
...
<div class="editor-field">
#Html.EditorFor(model => model.Wunschtermin)
#Html.ValidationMessageFor(model => model.Wunschtermin)
</div>
...
Edit:
Maybe I can override the RangeAttribute and avoid the problem:
[Range (DateTime.Now, DateTime.Today.AddYears(2))]
usefull?
have solved it myself, the code in the Controler was wrong:
[HttpPost]
public ActionResult Create(FormCollection collection)
with a smal change:
[HttpPost]
public ActionResult Create(Model1 collection)
it works well :-)

DataAnnotations driving client side validation issue

I am trying to get what I think is a simple example of using DataAnnotations on a model to drive the client side validation as well.
Here is my model...
public class Person
{
[Required(ErrorMessage = "First Name Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")]
public string LastName { get; set; }
}
Here is my controller...
public class FriendsController : Controller
{
public ActionResult Create()
{
Person newFriend = new Person();
return View(newFriend);
}
[HttpPost]
public ActionResult Create(Person friendToCreate)
{
if (ModelState.IsValid)
{
// todo -- do something here
return Redirect("/");
}
// Invalid - redisplay form with errors
return View(friendToCreate);
}
}
and here is my view...
#model MvcApplication4.Models.Person
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
</head>
<body>
<h2>
Create</h2>
#{Html.EnableClientValidation();}
#using (Html.BeginForm())
{
<fieldset>
<p>
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</p>
<p>
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
</body>
</html>
The server side validation works just fine and the validation error messages appear as expected. However, I am not getting the client side validation to work. Is there something obvious that I am missing to make the client side validation appear?
Did you enabled Client side Validation on your web.config file?
You can do it directly on the web.config file adding a couple of flags inside the appSetting section
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
or you can do it using pure c# code
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
I recommend you read Brad Wilson's article Unobtrusive Client Validation in ASP.NET MVC 3

Resources