Reputation: 3
As I am new to this MVC3 could not figure this out. Here is the situation -
I have a form. When a customer enters email address, onkeyup it checks where the email address already exists in the DB. If yes, I want to show a validation error messgae "Email already exists in the database" next to the textbox and I want to prevent user from submitting the form till the customer tries with a new email address. Rest of the validation rule I have set up in the model. But this one requires to check against the DB .
The problem is that I dont know how to overide the jquery validation and show a specific validation error message next to the textbox.
Can any one help me on this please?
many thanks in advance
Upvotes: 0
Views: 1190
Reputation: 1039110
You could use the [Remote]
attribute which allows you to perform this validation by sending an AJAX request to the server. The idea is to decorate your Email property on the view model with the Remote attribute indicating a controller action that will be invoked to validate:
[Remote("IsEmailAvailable", "Validation")]
public string Email { get; set; }
and then write a controller action to perform this validation:
public ActionResult IsEmailAvailable(string email)
{
if (CheckEmailAvailability(email))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("Sorry, the specified email is already taken", JsonRequestBehavior.AllowGet);
}
and then inside your view you will have the corresponding field:
<div>
@Html.LabelFor(x => x.Email)
@Html.EditorFor(x => x.Email)
@Html.ValidationMessageFor(x => x.Email)
</div>
It is important to mention that you need to perform the same check inside the controller action to which you are submitting the form because between the time the user verified for the last time whether the email is available and the time when the form has been submitted the email might already be taken by someone else:
[HttpPost]
public ActionResult ProcessFormSubmit(MyViewModel model)
{
// Warning this will not call the validation controller action specified
// by the Remote attribute
if (!ModelState.IsValid)
{
return View(model);
}
// now make sure you check for the email
if (!CheckEmailAvailability(email))
{
// the email is already taken
return View(model);
}
// at this stage the model is valid => you could process it
...
}
Upvotes: 1
Reputation: 5989
You can use [Remote] where you can easily provide a url to go to for validating the item. or else you can have your custom data annotation where you can write your custom logic.
The Remote attribute validation will get fired with the help of ajax when you enter content in the text box, however the custom attribute validation will get fired when you submit the content and call Model.IsValid() method. Happy coding
Link for how to use Remote Attribute
Upvotes: 1