nacho10f
nacho10f

Reputation: 5886

Problem with remote validation in asp.net mvc 3

I have a Person Model

public class Person
    {

        public int  ID { get; set; }
        [Required]
        [Remote("UserNameExists", "People", "Username is already taken.")]
        public string Name { get; set; }
        [Required]
        public string LastName { get; set; }



    }

This is my UserNameExists method

public JsonResult UserNameExists(string name)
        {
            bool exists = personRepository.GetPersonByName(name.Trim());
            if (!exists)
                return Json(true, JsonRequestBehavior.AllowGet);

            return Json(string.Format("{0} is not avavfddvilable.", name),
                    JsonRequestBehavior.AllowGet);
        }

When I have Javascript enabled it works just fine but when I disable javascript this rule is not enforced...

Why is this?

Please Help.

Edit for expected behavior:

According to msdn it should respect this rule even without Javacript

  1. Optionally, disable client script in your browser, run the page again, and enter data that violates the validation constraints.

As you leave the field that contains the invalid data, you do not see a validation error because scripting is disabled. Because ASP.NET MVC is using unobtrusive JavaScript, you do not see client-side script errors. However, server-side validation is performed when you submit the form. (It is a good practice to test your Web application with a browser that has scripting disabled.)

Upvotes: 0

Views: 2138

Answers (3)

RickAndMSFT
RickAndMSFT

Reputation: 22860

See my MSDN article How to: Implement Remote Validation in ASP.NET MVC I use the remote client validation code in the HttpPost Create method to test server side when JavaScript is disabled.

[HttpPost]
    public ActionResult Create(CreateUserModel model) {

        // Verify user name for clients who have JavaScript disabled
        if (_repository.UserExists(model.UserName)) {
            ModelState.AddModelError("UserName", ValidationController.GetAltName(model.UserName, _repository));
            return View("Create", model);
        }

Upvotes: 2

Adam Tuliper
Adam Tuliper

Reputation: 30152

You must duplicate a validation call on the server - this DOES NOT work as outlined as per my testing. See my post at: DRY Remote Validation in ASP.NET MVC 3

Upvotes: 1

p.campbell
p.campbell

Reputation: 100637

It sounds like you have JavaScript disabled, and your Remote Validation fails.

Remote Validation requires JavaScript enabled in the browser. It's using jQuery and an AJAX call to get this done.

The quote from MSDN is exactly what you're observing:

you do not see a validation error

server-side validation is performed when you submit the form

Upvotes: 0

Related Questions