How to avoid Repeated alert and What is the exact usage of HTML Validate
I tried to show an alert instead of span for error messages using Html
Validate, I achieved it, but the alert is getting repeated. If I leave the
text box field as empty and submitted the form at this situation the alert
is displayed.If I clicked somewhere in the browser the alert is getting
displayed once again. Along with this issue I really don't know what is
the exact usage of Html.Validate and ValidateFor because without these
html helpers the client side validation is occurring ,so where do we want
to use it. Please share some detailed knowledge about this. I was really
curious to understand these stuffs. Any help would be appreciated.Please
let me know if my question is unclear.
View:
<script type="text/javascript">
if (jQuery.validator) {
jQuery.validator.setDefaults({
showErrors: function (errorMap, errorList) {
alert(errorMap.LastName);
console.log("Error MAp" + errorMap.LastName);
}
});
}
</script>
<div>
@{Html.EnableClientValidation(true);}
@{Html.EnableUnobtrusiveJavaScript(true);}
@*Added JS libraries in the master page*@
@{Html.BeginForm("ValidatingFormMessages",
"ValidationMessage",FormMethod.Post, new { id = "USerFieldValid" });}
@Html.TextBoxFor(x => x.LastName, new { id = "txtLastName" })
@{Html.Validate("LastName");}
<input type="submit" id="btnSubmit" value="Submit" />
@{Html.EndForm();}
</div>
Model:
public class UserValidation
{
[Required(ErrorMessage="Last Name is required")]
[RegularExpression("^[a-z]+$",ErrorMessage="Enter only the Alpha
Characters")]
public string LastName { get; set; }
}
Controller:
public ActionResult ValidatingFormMessages()
{
UserValidation objValid = new UserValidation();
objValid.LastName = "j";
return View(objValid);
}
[HttpPost]
public ActionResult ValidatingFormMessages(UserValidation valid)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index", "Home");
}
return View();
}
No comments:
Post a Comment