Validation summary message pops up twice - javascript

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

Related

Need a javascript function to identify the which textbox used while clicking save button

I have 3 textboxes in 3 tabs of same ASP.net page and corresponding 3 javascript functions of same functionality. Presently I am using 3 different functions for three textboxes. I need only a single javascript function instead of three. Please help me
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd" ControlToValidate="textBox1" ErrorMessage="message" ClientValidationFunction="fname"></asp:CustomValidator>
Javascript functon
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
One way to do it would be checking which textbox value != "" and execute the send based on this
eg your onClick handler could contain this.
if(document.getElementById('<%=txtBox1.ClientID%>').value != ""){
do this
} else if (document.getElementById('<%=txtBox2.ClientID%>').value != ""){
do this
} else {
do this
}
Why don't you make one function that receives text box ID and call it from other 3:
function fname(textBoxID, sender, args) {
var x = document.getElementById(textBoxID).value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
When you call it for first text box, just pass '<%=txtBox1.ClientID%>' as first parameter. Same way, pass '<%=txtBox2.ClientID%>' for second text box...
There is another solution, you can find it more in detail here: Passing value from CustomValidator
In short it goes like this: use sender.id to get the id of the CustomValidator. Then so long as the validator's id is the id of the TextBox with a prefix of 'Validator_', I can use a javascript replace to get rid of the 'Validator_', therefore finding out the TextBox Id.

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); }

When checking if value is selected from dropdownlist it exits the page

I have a checkbox and a dropdownlist and I am trying to check that if the checkbox is ticked, a value has been selected from the dropdownlist. That works fine but if the alert message pops up and I click OK to remove the message, it exits out of the page I was in. I want to say on the page same, I don't know why it is redirecting me somewhere else. Also if possible I would prefer if the error message ErrorMessage = "Please select" appeared instead of the alert box but that isn't the main issue here.
<tr>
<td class="Header">License Type</td>
<td></td>
<td>
<asp:DropDownList runat="server" ID="ddlHazLicenseType" CausesValidation="true" >
</asp:DropDownList>
<asp:CustomValidator id="CustomValidator2" runat="server"
ControlToValidate = "ddlHazLicenseType"
ErrorMessage = "Please select"
ValidateEmptyText="True"
ClientValidationFunction="validateHazLicenceType" >
</asp:CustomValidator>
</td>
</tr>
function validateHazLicenceType()
{
if (document.getElementById("<%=chkHazTrained.ClientID %>").checked)
{
var ddl = document.getElementById("ddlHazLicenseType");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if ($("#ddlHazLicenseType")[0].selectedIndex <= 0)
{
alert("Please select a licence type");
}
}
}
Try something like
function validateHazLicenceType(oSrc, args) {
if (document.getElementById("<%=chkHazTrained.ClientID %>").checked) {
var ddl = document.getElementById("<%=ddlHazLicenseType.ClientID %>");
if (ddl.selectedIndex <= 0) {
args.IsValid = false
}
}
}
CausesValidation="true" seems to only cause validation when the selected index changes - which means if the initial selection is index 0, and the user never changes it, it won't validate as intended. You could try setting the DDL's selected index to -1 (so nothing is selected), but I don't think that solves the problem. You'll probably have to validate the DDL value somewhere else - on submission, perhaps?
Its been a while since I last worked with asp, and it would be nice to see the actual source (html) code. Anyway, 2 things come to mind:
1) Have your validation js function return false at the end
what happens is your validation function assumes the validation passed, and submits right after that. Returning false would prevent that to happen ( good thing to know on the side: return false means you stop the default action and stops event propagation)
2) Your submit onchange for the DDL may be somehow turned on

test if page is valid before running 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();" />

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;
}

Categories

Resources