problem i have is that, the validation summary message(alert) is displayed twice. I cannot figure out the reason.
Please help.
Here is the code
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
}
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"
ValidationGroup="ContactGroup" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
The problem is that the function Page_ClientValidate takes an input parameter, if you don't specify the input then the validationsummary triggers once per groupname.
In your case, the function triggers twice: once for groupname="ContactGroup" and another time for groupname=""
you should change
var isPageValid = Page_ClientValidate();
to
var isPageValid = Page_ClientValidate('');
if you don't want to specify a ValidationGroup, or if you want to specify a groupname then you need to call Page_ClientValidate like so:
var isPageValid = Page_ClientValidate('ContactGroup');
First of all you should lose the ValidationGroup="ContactGroup" from the button because having validation group in it will first call of the validation on the page then the OnClientClick event that contains the validate function which will call the page validation once again.
Then you should pass the validation group "ContactGroup" to the Page_ClientValidate() function so it knows which controls to validate because simply calling Page_ClientValidate() will validate all controls regardless of their validation group(and it may display the validation message more than once, depending on how many validation groups you have).
In short do something like this:
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate('ContactGroup');
if(isPageValid)
{
//your custom code
}
}
}
<asp:textbox id="txtMyBox" runat="server"/>
<asp:requiredFieldValidator Id="rfv1" runat="server" ControlToValidate="txtMyBox"
ValidationGroup="ContactGroup" ErrorMessage="Bad!"/>
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"/>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
just return false from the function and change the OnClientClick as shown below:
<asp:Button ID="btn1" runat="server" OnClientClick="return validate();" Text="button"
ValidationGroup="ContactGroup" />
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
return false;
}
There is no need to manually call the Page_ClientValidate function, unless you're wanting to do the validation outside of a postback attempt.
Set the buttons CausesValidation to true. That'll run the validation.
You can make validation without show messages, use the following code segment,then use isPageValid variable:
if (Page_ValidationSummaries && Page_ValidationSummaries[0] && Page_ValidationSummaries[0].showmessagebox) {
var showMessagesOption = Page_ValidationSummaries[0].showmessagebox;
Page_ValidationSummaries[0].showmessagebox = "False";
isPageValid = Page_ClientValidate();
Page_ValidationSummaries[0].showmessagebox = showMessagesOption;
}
I know this is an old post, but here's a solution that may be more flexible. Similar to other users suggestions, this solution accepts the validation group that is passed by default by the asp.net validation controls. This way you would not need to add the OnClientClick="validate()" on the Button control.
//Make sure the Page_ClientValidate function exists
if (typeof (Page_ClientValidate) == "function") {
//Stash the old implementation in a temp variable
Page_ClientValidateOld = Page_ClientValidate;
//Create a new implementation and store it
//in Page_ClientValidate. Callers will now get
//this implementation.
Page_ClientValidate = function (validationGroup) {
var isValid;
//Call the old implementation first…
isValid = Page_ClientValidateOld(validationGroup);
//and then call our extension
if (!isValid) {
// Do something
}
return isValid;
}
}
If you want to read more on this approach, I recommend that you look at this blog post:
http://hyperthink.net/blog/interception-patterns-in-javascript/
Remove the click event of the button, that forces second validation I think.
remove the onclientclick event of button there is no need for that
Related
I want to disable the form submit button when asp:RequiredFieldValidator shows error
please advise
if(Page_ClientValidate("SomeValidationGroup") == false)
document.getElementById("button1").disabled = true;
You could use this javascripot function onchange of the control which triggers validation:
<asp:TextBox id="TextBox1" runat=server OnChange="txtValidate();" />
<asp:RequiredFieldValidator id="validator1" runat="server"
ControlToValidate="TextBox1" ...>
<script>
function txtValidate() {
// trigger validation from clientside
var val = <%= validator1.ClientID %>;
if (val.isvalid == false) {
document.getElementById('btnSubmit').disabled = true;
}
}
</script>
Perhaps you can try something like this:
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
//disable button here
return false;
}
//enable button here
return true;
}
For more information about this function visit and understanding the ASP.NET Validation Library visit this post.
Alternatively, as #Nag suggested, a custom validator may also be able to accomplish this as you are able to define the client side JavaScript.
You should use validationgroup + requirevalidation then the button should not be clickable
I want to run whatever client-side validation routine is hooked up to a particular text input element.
The validation has been set up using CustomValidator:
<asp:textbox id="AddEstTime" runat="server" Width="55px"></asp:textbox><br />
<asp:CustomValidator ID="AddEstTimeCustomValidator" ClientValidationFunction="AddEstTimeCustomValidator_ClientValidate" OnServerValidate="AddEstTimeCustomValidator_ServerValidate" ErrorMessage="Please enter a time" ControlToValidate="AddEstTime" runat="server" Display="Dynamic" ValidateEmptyText="true"/>
<asp:CheckBox ID="AddIsTM" runat="server" Text="T&M" />
and the javascript:
function AddEstTimeCustomValidator_ClientValidate(sender, args) {
var checkbox = $("input[id$='IsTM']");
args.IsValid = checkbox.is(":checked") || args.Value.match(/^\d+$/);
}
When the CheckBox "AddIsTM" state changes, I want to revalidate the textbox "AddEstTime", using its hooked-up CustomValidator "AddEstTimeCustomValidator".
I am aware of focus -> add a character refocus -> remove character. I am trying to find a more correct way. New to asp.NET.
After looking through the Microsoft client-side code, I came up with this which seems to work:
// client-side validation of one user-control.
// pass in jquery object with the validation control
function ValidateOneElement(passedValidator) {
if (typeof (Page_Validators) == "undefined") {
return;
}
$.each(Page_Validators, function (index, value) {
if ($(value).attr("id") == passedValidator.attr("id")) {
ValidatorValidate(value, null, null);
}
});
}
This was after examining the Page_ClientValidate function:
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
thx sennett (voted)
i just ran the simplest JS
Page_ClientValidate();
if you have a validation group then is
Page_ClientValidate("validationGroupName")
If you want stick with ASP.NET validators eventually you can abuse Validation Groups, but I think that this approach will give you nothing but trouble. Other option is to use jQuery on the client (nice list) only then you will have to duplicate validation on the server side, or to avoid that call server methods from client validations.
I would like to have a Javascript function to be called when ever my required field validator control is true (i.e when the validator control is fired / error message shown).
Kindly let me know how this can be done.
Thanks in advance.
You can call a JS function on OnClientlick of the button.
for ex.
function CheckValidation()
{
if (Page_ClientValidate())
{
// Call Your custom JS function and return value.
}
}
// Calling JS function
<asp:Button ID="btnSubmit" runat="server"
OnClientClick="return CheckValidation();" />
Assuming you're validating a TextBox control, the following snippet should do what you want:
<asp:TextBox id=txtZip runat=server OnChange="txtZipOnChange();" />
<asp:RegularExpressionValidator id="valZip" runat="server"
ControlToValidate="txtZip" ...>
<script>
function txtZipOnChange() {
// get the validator and check if it is valid
var val = <%= valZip.ClientID %>;
if (val.isvalid == false) {
// do something
}
}
</script>
Use CustomValidator control. Set the CustomValidator.ClientValidationFunction property to the javascript function and the CustomValidator.ValidateEmptyText property to false.
In my aspx page in a submission form i have following html.
<p><asp:CheckBox ID="chkWishToDonateFrmTrust " runat="server" onclick="chkWishToDonateFrmTrustHandle(this)" />
Wish to donate from following Trust for future transactions</p><p> </p><p><textarea name="textarea" cols="45" rows="5" class="txtTrustDetails" runat="server"
id="txtTrustDetails" ></textarea></p>
I need to have a required field validation control to validate txtTrustDetails text area only if chkWishToDonateFrmTrust is checked by the user without server post backs for this.only javascript library I am using is Microsoft Ajax Framework.I also have to include this to validation group in form with some other for controls.I already know as my knowledge one required field validator control can only validate single UI control(asp.net forum thread) does anyone in community dealt with this kind of issue in intuitive way?
As another answer has said, use a Custom Validator and do something like this (not tested so may not be quite right...):
<script type="text/javascript">
function validate(sender, args) {
var checkBox = document.getElementById('<%=CheckBox1.ClientID %>');
var textBox = document.getElementById('<%=TextBox1.ClientID %>');
if (checkBox.checked == 1) {
if (textBox.value == '') {
args.IsValid = false;
} else { args.IsValid = true; }
}
}
</script>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" runat="server"
ErrorMessage="CustomValidator" ClientValidationFunction="validate"></asp:CustomValidator>
Use the custom validator and use the clientValidationfunction to call a javascript function to check your values.
You should also have a servervalidate function incase javascript is off.
you can use a js function or a jquery function to do this is a sample code of how to achieve this
function chkValidate()
{
if($("#chkWishToDonateFrmTrust ").checked)
{
if($("#txtTrustDetails").val()=='')
{
args.IsValid = false;
//your custom message according to you
}
}
}
call this function on your sumbit button onclick;
I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.