I am working on a brownfield site that fires asp.net clientside validation, whatever the result it always does a postback. Has anybody any ideas to stop this behavior if it fails the validation?
Thanks in advance.
Podge
You can leverage Custom Validator control w3schools or MSDN link. It allows you to perform client side validation. Usage example.
<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckEven" /><br>
Input:
<asp:TextBox id="txtCustomData" runat="server" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
I was getting the same behavior and fixed it by setting the CausesValidation property to True.
just for example: validate the textbox , if its empty postback not called else postback called.
button click event:
<asp:TextBox id="vTextBox" runat="server" />
<asp:button id="okButton" runat="server OnClick="okButton_Click" OnClientClick=" return isValidate();"/>
<script type="text/javascript">
function isValidate() { var txt = $("#vTextBox").val();
if ( txt === "") { alert("error"); return false; }
else { alert(" no error "); return true; } }
</script>
In my case I had a couple of CustomValidators where the ClientValidationFunction was missing.
Ensure there are no JavaScript errors on the page which could also cause this problem.
For Client Validation you must be calling some JS function for validation:
If you are calling the client side validation method on a button click then you should call it like below:
<asp:Button runat="server" id ="btnSubmit" onClientClick="return ValidateForm();" >
And the Validate Form method should return true or false.
like :
function ValidateForm()
{
/// Validation goes here
if (validated)
{
return true;
}
else{
return false;
}
}
}
Related
I've got an assignment for school in which two textboxes have to be the same, exactly the same as using a compare validator but instead we have to use a custom validator.
The code I used so far is:
protected void CustomValidator1_ServerValidate1(object source, ServerValidateEventArgs args)
{
if (TextBox2.Text == TextBox3.Text)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
and in ASP.NET
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="The second and third haven't got the same input."
onservervalidate="CustomValidator1_ServerValidate1"
ValidateEmptyText="True" ValidationGroup="Custom"></asp:CustomValidator>
But when I debug the webform nothing shows up when I fill in two different inputs.
The controls won't be validated until you attempt to submit the form to the server; they won't be validated as soon as they are edited.
You can specify AutoPostback to be true to cause the form to be submitted to the server every time the textboxes are edited, but that's likely to cause its own set of problems.
To have the form be validated entirely on the client, without posting to the server, you'll need to write that JavaScript code yourself, rather than a custom validator.
To enable client side (before posting back) validation with a CustomValidator, you must set the ClientValidationFunction to some JavaScript.
Something like:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="The second and third haven't got the same input."
onservervalidate="CustomValidator1_ServerValidate1"
ClientValidationFunction="CustomValidator1_ClientValidate1"
ValidateEmptyText="True" ValidationGroup="Custom"></asp:CustomValidator>
<script type="text/javascript">
function CustomValidator1_ClientValidate1(source, arguments) {
if (/* validation code */) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
Im struggling getting this to work the way i need. I have two RequiredFieldValidators and two textboxes (Side note: although i have Javascript below i dont mind doing this in another way. I did try code behind but realised validation didnt kick in until i clicked a button twice):
<asp:TextBox ID="EmailTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailR" runat="server" ErrorMessage="Email" ControlToValidate="EmailTextbox" ></asp:RequiredFieldValidator>
<asp:TextBox ID="NameTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="NameR" runat="server" ErrorMessage="Enter your name" ControlToValidate="NameTextbox" ></asp:RequiredFieldValidator>
I then have some script
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($(this).val() != '') {
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
}
else
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
});
});
</script>
What im trying to do is:
If EmailTextbox has an email then disable NameTextbox validation.
If EmailTextbox has NO email then enable NameTextbox validation and disable EmailTextbox validation.
With me being pretty new to JQuery/Javascript i have tried several attempts in trying to achieve the above however reading more into it, theres a possibility that i could have the wrong JQuery file (that said with this being an existing project i havent really added any ref to any JQuery so it could well be that i have the code right but need a ref to a JQuery or need to include a new version).
Overall if i can
Thanks
You can try it
$(document).ready(function () {
$('#<%=EmailTextBox.ClientID%>').keyup(function () {
if ($(this).val() != null && $(this).val().length != 0) {
$('#<%= NameRequiredFieldValidator.ClientID%>').hide();
}
else {
$('#<%= NameRequiredFieldValidator.ClientID%>').show();
$('#<%= EmailRequiredFieldValidator.ClientID%>').hide();
}
});
In your code you make the validation enable wrongly when a email
value was not null disable validation on name and enable for email else viceversa
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($.trim($(this).val()).length)
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), true);
}
else
{
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), false);
}
});
});
</script>
You can try this, similar to what you had.
function doSomething()
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
Or, you could use the visible=true/false on them which renders them inactive (meaning set visible property from code behind).. This might cost you an ajax trip to the code behind using scripmanager and __doPostBack in order to call a server-side function that can than process your logic... A lot of developers don't realize that at least in webforms, you can call your code behind methods from JS, just be very careful - as each call back can get costly...
A good article on communicating from ("front end to code behind via JS") -
http://www.codedigest.com/Articles/ASPNET/320_Doing_or_Raising_Postback_using___doPostBack()_function_from_Javascript_in_AspNet.aspx
Hope that helps or get's you back on the right track!!!
So I'm having some trouble. Even after trying many different solutions my problem is still persistent.
The button click will fire the java script code, but not the server side code.
<asp:Button ID="btnSubmit" runat="server" CssClass="ins_sub_btn_form_map" OnClientClick="javascript: stripeSubmit(); return true;" onClick="btnSubmit_Click"
UseSubmitBehavior="false" ValidationGroup="Submit" Text="Submit" />
here's my javascript:
function stripeResponseHandler(status, response) {
if (response.error) {
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#form1");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='visible' id='stripeToken' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
function stripeSubmit() {
Stripe.setPublishableKey($("input#txtStripePK").val());
var expDate = $("input#txtExpirationDate").val();
if (Stripe.card.validateCardNumber($("input#txtCreditCardNumber").val()) == false)
{
alert("Credit Card Number Error");
return;
}
if (Stripe.card.validateCVC($("input#txtCVVNumber").val()) == false) {
alert("CVN Number Error");
return;
}
if (Stripe.card.validateExpiry((expDate.slice(0, 2)) , ("20" + expDate.slice(2, 4))) == false) {
alert("Expiration Date Error");
return;
}
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.card.createToken({
number: $("input#txtCreditCardNumber").val(),
cvc: $("input#txtCVVNumber").val(),
exp_month: (expDate.slice(0, 2)),
exp_year: ("20" + expDate.slice(2, 4))
}, stripeResponseHandler);
//return true; // submit from callback
}
I've tried it without the return true in javascript, with it in javascript. Also tried it without the return true in the onClientClick, also without the "javascript:". Literally everything I can think of.
Any help is appreciated. Thanks in advance.
If I'm not mistaken, by default, asp control's UseSubmitBehavior property is set to true. This means any event performed on that control will cause a postback. You have UseSubmitBehavior set to false so the code behind will never get executed since no postback occurs. When using OnClientClick() and OnClick() together, the client side code will execute first and then the server side code. Hope this helps
Use closing () on the method inside your Onclick. ex onClick="SomeMethod()"
i have hiddentfield whose value is changing on javascript.
I just wanted to fire serverside event valuechanged event of hiddenfield when its value changed from javascript.
I tried with :
__doPostBack('hfLatitude', 'ValueChanged');
But giving me error :
Microsoft JScript runtime error: '__doPostBack' is undefined
Is there any other alternative for this?
Please help me.
In javascript, changes in value to hidden elements don't automatically fire the "onchange" event. So you have to manually trigger your code that is already executing on postback using "GetPostBackEventReference".
So, with a classic javascript approach, your code should look something like in the example below.
In your aspx/ascx file:
<asp:HiddenField runat="server" ID="hID" OnValueChanged="hID_ValueChanged" Value="Old Value" />
<asp:Literal runat="server" ID="litMessage"></asp:Literal>
<asp:Button runat="server" ID="btnClientChage" Text="Change hidden value" OnClientClick="ChangeValue(); return false;" />
<script language="javascript" type="text/javascript">
function ChangeValue()
{
document.getElementById("<%=hID.ClientID%>").value = "New Value";
// you have to add the line below, because the last line of the js code at the bottom doesn't work
fValueChanged();
}
function fValueChanged()
{
<%=this.Page.GetPostBackEventReference(hID, "")%>;
}
// the line below doesn't work, this is why you need to manually trigger the fValueChanged methiod
// document.getElementById("<%=hID.ClientID%>").onchange = fValueChanged;
</script>
In your cs file:
protected void hID_ValueChanged(object sender, EventArgs e)
{
litMessage.Text = #"Changed to '" + hID.Value + #"'";
}
Quick and Dirty:
Simply put a asp button on form. Set it display:none.
<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />
On its click event call any server side event.
protected void xyx_Click(o,e)
{
//you server side statements
}
To call its from JS use as below:
<script>
function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}
function anyotherjsfunc()
{
//some statements
myserverside_call();
}
</script>
First way is to use HiddenField.ValueChanged Event.
If you want to also watch this varible in Client Side just use this:
$('#hidden_input').change(function() {
alert('value changed');
});
Second way is to assign value to Varible:
$('#hidden_input').val('new_value').trigger('change');
How can i get the value that was pressed in the confirm box?
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
if (confirm("Are you sure you want to proceed?")==true)
return true;
else
return false;
}
</script>
C#
Button2.Attributes.Add("onclick", "return confirm_proceed();");
Try this, if this is the only button that has this behavior
Button2.Attributes.Add("onclick", "return confirm('Are you sure you want to proceed?')");
it's inline and looks straightforward but if you have multiple controls that behave this way then your original approach would be easy to maintain.
And your original function could be shrunken to
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
return confirm("Are you sure you want to proceed?");
}
</script>
You can store the value of confirm_proceed() in an asp:HiddenField
You can modify your script as follows:
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
var hiddenField = document.getElementById('hiddenFieldId');
if (confirm("Are you sure you want to proceed?")==true)
{
hiddenField.value = 'true';
return true;
}
else
{
hiddenField.value = 'false';
return false;
}
}
</script>
You can now access first the hidden field's value in your Button2_Click event.
I just face similar problem in a real production project and I solved it by the following:
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" onClientClick="return confirm('Are you sure you want to proceed?')"/>
so the OnClientClick Client event is raised befoere the onClick which is a server event , so if the user clicks OK then the Client event returns True from the confirm Dialog and therefore the Code Behind this button is executed , on the other hand if the user clicks (Cancel or No) then it would return false and therefore the code behind wont get exected (Server Event is Cancelled)
hope it would help you as I really applied it to my project and worked without any issues.