test if page is valid before running javascript - javascript

I have some javascript that "freezes" the screen when a submit button is pressed. This is to stop double clickers.
I have discovered that there is an issue if a validator control returns false, in that, the screen has "frozen", so the user can't fix the problem with their input data.
I need to be able to tell if the page is valid or not, so that if it is not, i can un-freeze the screen.
How can I do this??
javascript code that freezes the screen... (originally from 4guysfromrolla)
function FreezeScreen(msg) {
var outerPane = document.getElementById('FreezePane');
var innerPane = document.getElementById('InnerFreezePane');
if (outerPane) outerPane.className = 'FreezePaneOn';
}
code that runs the javascript...
<asp:Button ID="btnSubmit" runat="server" Text="<%$ Resources:LocalizedText, button_SubmitOrder %>" onclick="btnSubmit_Click" ValidationGroup="validateHeader" OnClientClick="FreezeScreen();" />

It will probably be something like this.
function ValidatePage() {
FreezeScreen();
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
UnFreezeScreen();
return true;
}
else {
UnFreezeScreen();
return false;
}
}
And on the button
<asp:Button ID="btnSubmit" runat="server" Text="<%$ Resources:LocalizedText, button_SubmitOrder %>" onclick="btnSubmit_Click" ValidationGroup="validateHeader" OnClientClick="return ValidatePage();" />

Related

How to validate a CheckBox with CustomValidator within a RadListView

I have a Telerik:RadListView control and multiple checkboxes in it. I need to validate those checkboxes before submitting the form.
I have tried build-in validators with ControlToValidate property but it gave me the error Control 'chkQuestion' referenced by the ControlToValidate property of 'chkQuestionValidator' cannot be validated. which is very logical because they are all in a RadListView.
After that, i created a CustomValidator;
<asp:CheckBox ID="chkQuestion"
CssClass="AcceptedAgreement"
Visible="true"
runat="server"
Text=" I confirm"
AutoPostBack="false" />
<asp:CustomValidator
ClientValidationFunction="CheckBoxRequired_ClientValidate"
EnableClientScript="true"
ID="chkQuestionValidator"
runat="server"
Enabled="true"
SetFocusOnError="true"
ErrorMessage="Please confirm"
ForeColor="Red" />
these are all in Telerik:RadListView which means i have multiple of them but i cant link them in my client-side custom validator function.
Here is my validator function:
function CheckBoxRequired_ClientValidate(sender, e) {
var c = jQuery(".AcceptedAgreement input:checkbox");
var chb = validator
if (c.is(':checked')) {
e.IsValid = true;
} else {
e.IsValid = false;
}
}
but with this function i cant validate them seperately. when one of the checkboxes checked, this function act like all of them are checked. this is because they all have same css class, and this is the point i stucked.
if you help me, it will be appreciated.
For those who come here for solution, here it is:
function handleSubmitForm(sender, args) {
var c = jQuery(".AcceptedAgreement input:checkbox");
c.each(function (index) {
if (!c[index].checked) {
args.set_cancel(true);
}
});
args.set_cancel(true);
}
basically i assign this piece of code to my button, it is called before doing postback, and if it does not fit my condition, it stops the postback. you can do whatever you want in if clause.
you can call this function :
<telerik:RadButton ID="btnSubmit"
OnClientClicking="handleSubmitForm"
Text="Submit" OnClick="btnSubmit_Click" />

Converting from OnClientClicking to onClientClick

I currently have a JavaScript method that looks to see if the page is validated and if so allows the user to press a create button and throws a radconfirm, the problem i am having is that if i use a radButton this works perfectly but when using an ASP:Button it wont allow the radConfirm to show up and skips past it.
This is the method:
function ShowConfirm(clickedButton, args) {
var validated = window.Page_ClientValidate('POPgroup');
if (validated)
{
args.set_cancel(true);
function confirmCallBackFn(arg) {
if (arg == true) {
clickedButton.click();
}
}
var text = "Please make sure all fields are completed correctly as once" +
" accepted the proof of purchase will be submitted and no further " +
"changes will be allowed. Are you sure you wish to continue?";
radconfirm(text, confirmCallBackFn,350,100,null,"Confirm");
}
}
This is the button:
<asp:Button ID="AddProofOfPurchaseButton" runat="server" Text="Submit"
ValidationGroup="POPgroup" CssClass="claim_header_create_button"
OnClick="AddProofOfPurchaseButton_OnClick" OnClientClick="ShowConfirm(this);
return false;" />
How would i change this code to work with the asp button and not the radbutton? also why does this happen what is the difference between OnClientClicking(Telerik) to onClientClick(asp)
For anyone else that stumbles across the same problem the answer i found to my problem was this.
function ShowConfirm(button) {
var validated = window.Page_ClientValidate('POPgroup');
if (validated) {
function CallbackFn(arg) {
if (arg) {
__doPostBack(button.name, "");
}
}
var text = "Please make sure all fields are completed correctly as once" +
" accepted the proof of purchase will be submitted and no further " +
"changes will be allowed. Are you sure you wish to continue?";
radconfirm(text, CallbackFn, 350, 100, null, "Confirm");
}
}
And the button like this:
<asp:Button ID="AddProofOfPurchaseButton" runat="server" Text="Submit"
ValidationGroup="POPgroup" CssClass="claim_header_create_button"
OnClick="AddProofOfPurchaseButton_OnClick" OnClientClick="ShowConfirm(this); return false;" />
I also faced this problem few days back. Actually Radbutton's are set true for Autopostback by default, so if you want to achieve this in radbutton! then,
you need to change the postback property (you can change it in jscript later) and also the causesvalidation check.
<telerik:RadButton ID="AddProofOfPurchaseButton" Text="Submit" CssClass="claim_header_create_button" runat="server"
ValidationGroup="POPgroup" OnClientClicking="ShowConfirm" CausesValidation="false" AutoPostBack="false" OnClick="AddProofOfPurchaseButton_OnClick"></telerik:RadButton>
and also in script
function confirmCallBackFn(arg) {
if (arg == true) {
clickedButton.set_autoPostBack(true); //removed -->clickedButton.click();
} else { clickedButton.set_autoPostBack(false); }

Disable dx aspxbutton

I'm trying to set a button's enable/disable based on a checkbox being checked or not. Below is my javascript and asp code, which doesn't work. I am not sure if the function is not called at all, or something is wrong with how I disable the button.
<script type="text/javascript">
function OnChkAgreeChanged(chkAgree) {
if (document.getElementById"chkAgree").checked)
document.getElementById("btnSubmit").SetEnabled(true);
else
document.getElementById("btnSubmit").SetEnabled(false);
}
</script>
<asp:checkbox ID="chkAgree" runat="server"
Text="blablabla" onchange="javascript:OnChkAgreeChanged(this);"/>
<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit"
UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>
DevExpress creates a client instance object for each one of it's various controls. In this case it will create an ASPxClientButton for btnSubmit. Since you haven't given btnSubmit a ClientInstanceName, you can access it like so:
window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];
That means your entire handler function could look something like this:
function OnChkAgreeChanged(chkAgree)
{
btnSubmit = window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];
if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}
You could also make your life easier by defining the ClientInstanceName attribute like so:
<dx:ASPxButton ID="btnSubmit" ClientInstanceName="btnSubmit" runat="server" Text="Submit"
UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>
Then, you'd be able to use that directly in your handler:
function OnChkAgreeChanged(chkAgree)
{
if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}
You'll note that I like to check if that thing is null or not because if you set the display to none in the Code-Behind or otherwise disable it, it's very likely the DevExpress magic/voodoo (pick one) won't emit the JS creating that instance object.
chkAgree is an object not a string. You don't have to use document.getElementById. Try this...
<script type="text/javascript">
function OnChkAgreeChanged(chkAgree) {
if (chkAgree.checked)
document.getElementById("btnSubmit").disabled = null;
else
document.getElementById("btnSubmit").disabled = true;
}
</script>
Also, in onchange="javascript:OnChkAgreeChanged(this);" javascript: may not be required. Pls check ASP documentation.
JQuery Solution
$(document).ready(function () {
$('#chkAgree').click(function () {
if (this.checked) {
$("#btnSubmit").prop('disabled', false);
}
else {
$("#btnSubmit").prop('disabled', true);
}
});
});
Or if you want to do same thing using JavaScript can use solution suggested by mohkhan.
Use the ClientInstanceName and ClientEnabled (not the Enabled) properties for this purpose:
function OnChkAgreeChanged(chkAgree) {
var checked = chkAgree.checked;
btnSubmit.SetEnabled(checked);
}
</script>
<asp:checkbox ID="chkAgree" runat="server" Text="blablabla" onchange="OnChkAgreeChanged(this);"/>
<dx:ASPxButton ... ClientInstanceName="btnSubmit" ClientEnabled="False">
</dx:ASPxButton>

Javascript validation overwrites ASP.NET validators

I have a problem that is making me crazy. On my page I have one Javascript validation and two ASP.NET validators. The validation outcome depends just on the result of the Javascript. That means if the Javascript returns true the ASP.NET validators are not checked.
The Javascript code is:
<script type="text/javascript">
function Validate() {
var ddlObj = document.getElementById('<%=ddStatus.ClientID%>');
var txtObj = document.getElementById('<%=txtComment.ClientID%>');
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
return false;
}
}
}
</script>
Instead the two ASP.NET validators are:
<td><asp:TextBox runat="server" ID="txtSerialNr" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtSerialNr" ErrorMessage="***" />
</td>
<td><asp:TextBox runat="server" ID="txtProdName" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="txtProdName" ErrorMessage="***"></asp:RequiredFieldValidator></td>
Anybody might help? Thanks
UPDATE:
I call the Javascript from a button:
<asp:Button runat="server" ID="btnSubmit" Text="Save New Product"
style="cursor:hand" OnClick="btnSubmit_Click" />
But I register the attribute from the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("OnClientClick", "return Validate()");
}
You can fire the client side validation from within the Validate() function:
validate = function(){
bool isValid = Page_ClientValidate(""); //triggers validation
if (isValid){
var ddlObj = document.getElementById("<%=ddStatus.ClientID%>");
var txtObj = document.getElementById("<%=txtComment.ClientID%>");
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
isValid = false;
}
}
}
return isValid;
}
Markup:
<asp:Button runat="server" OnClientClick="return validate();" ... />
OK, there's a couple of things wrong here.
If you are concerned enough to do validation, you must ALWAYS do server-side validation in addition to client-side. Client-side validation is very user-friendly and fast to respond, but it can be bypassed simply by setting JavaScript to 'off'!
I don't see where you've told your controls which JavaScript function to call when they validate? You use RequiredFieldValidators which don't require an external function - but then attempt custom validation using your Validate() function.
If you do end up using a CustomValidator, then you'll need to change the 'signature' of your function. It needs to be of the form
function validateIt(sender, args){
var testResult = //your validation test here
args.IsValid = testResult;
}

Validation summary message pops up twice

I have validation controls in my page and I am using Validation summary message box to display the validation messages,the javascript function shown below worked for me but the problem is I am using this javascript function on OnClientClick event of the button and when I click the button with form controls not been filled its displaying the validation summary message box as expected but when i close the summary box it's getting displayed again and i need to close the message box to disappear, means i have to do two clicks everytime. Can somebody correct me what am I doing wrong.
Here is what I am doing:-
<asp:Button ID="SubmitButtonOne" runat="server" Text="Submit" OnClick="SubmitButtonOne_Click"
ValidationGroup="Cases" ClientIDMode="Static" OnClientClick="PleaseWaitShow()" />
Here is the javascript function:
function PleaseWaitShow() {
var isPageValid = true;
// Do nothing if client validation is not active
if (typeof (Page_Validators) != "undefined") {
if (typeof (Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate();
}
}
if (isPageValid) {
document.getElementById('SubmitButtonOne').value = "Processing...";
}
}
code behind:
protected void SubmitButtonOne_Click(object sender, EventArgs e)
{
try
{
// some functionality
}
catch (Exception)
{
//show errror message
}
}
It is expected behavior.
Once Page_ClientValidate is fired due to your explicit call inside PleaseWaitShow method and second is an implicit call made by the PostBack button click.
And so you are seeing two times the ValidationSummary message box.
I don't have a solution to circumvent this but will update if something strikes.
Note: One thing I would like to point out is since you have ValidationGroup="Cases" on your submit button you should pass that to your Page_ClientValidate method.
Update 1: One way I can think of is trying something like this:
1: OnClientClick="return PleaseWaitShow();"
2: return isPageValid from PleaseWaitShow():
function PleaseWaitShow() {
var isPageValid = true;
....
....
....
return isPageValid;
}
No, it is not the expected behavior. Rather, it's a bug in ASP.NET validation JS code.
The ValidationSummaryOnSubmit function loops over all summaries, and for each summary, loops over all validators. If not group is specified, then each validator's message is appended, resulting in 2 (3, 4, 5?) repetitions of the same messages.
I solved the problem by fixing the function (staring at line 53 or so):
....
for (i = 0; i < Page_Validators.length; i++)
{
var validator = Page_Validators[i];
if (validator.validationGroup != null && summary.validationGroup != null)
{
if (validator.validationGroup != summary.validationGroup) continue;
}
if (!validator.isvalid && typeof (validator.errormessage) == "string")
{
s += pre + validator.errormessage + post;
}
}
....
if you use Page_ClientValidate method, you should set causevalidation to false. CausesValidation="false"
because Page_ClientValidate is already doing this for button or control you validate
Please remove ValidationGroup of Button. Only user for ValidationSummary
Like:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqvName" runat="server" ControlToValidate="txtName" ErrorMessage="Please enter Name" ValidationGroup="SaveName"> </asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" OnClientClick="DisableButton();" Text="Save this Name" ></asp:Button>
<asp:ValidationSummary ID="valSaveName" runat="server" ValidationGroup="SaveName" ShowMessageBox="true" ShowSummary="false" />
Thanks

Categories

Resources