Reputation: 89
I have custom control with ASP.Net validators.
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:return DoSmth();");
function DoSmth() {
var cBox = confirm("Are you sure?");
if (!cBox) {
return false;
}
else {
//Invoke validation
}
When I push button submit, I call confirm box. If I press cancel - all right. But if I press ok, I need to do validation. How can I stop postback and do valiadation?
Upvotes: 2
Views: 4055
Reputation: 32343
Call client-side Page_ClientValidate(validationGroup)
. It returns true
if the page was valid.
function DoSmth() {
var cBox = confirm("Are you sure?");
if (!cBox) {
return false;
}
else {
return Page_ClientValidate(validationGroup);
}
}
EDIT(an answer to a comment):
validationGroup
here is a string variable, and it is not necessary to pass it to DoSmth
function (honestly, the answer should be: it depends).
If this function is defined in a .js
file, then yes, validationGroup
should be passed as an argument.
If it is a part of the page/control it would be easier to use e.g. server side constructions here:
return Page_ClientValidate('<%= btnSubmit.ValidationGroup %>');
where btnSubmit
is a button which causes validation, or use just a string variable.
Upvotes: 4
Reputation: 4473
I am not sure if you can stop a postback with ASP.Net Validation. From MSDN:
"Validation occurs after page initialization (that is, after view state and postback data have been processed) but before any change or click event handlers are called. "
I use jQuery Validation and then check the value in the same method as the confirm dialog.
function DoSmth() {
$('#form1').validate({
rules: { field: "required" }
});
var cBox = confirm("Are you shure?");
if (cBox && $('#form1').valid() ) {
//form is valid
}
else {
return false;
}
Upvotes: 0