ASP.NET server side validation not firing - c#

In My Application server side validation function is not working.even function is not called. i have put debugger on thuat function but it is not stopped ny debugger .i.e. function is not called
<asp:TextBox type="text" ID="txtMobilePhone" runat="server" ClientIDMode="Static" CausesValidation="true"/>
<asp:CustomValidator ID="cvMobilePhone" runat="server" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" ControlToValidate="txtMobilePhone" CssClass="error"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="rfvMobilePhone" runat="server" ControlToValidate="txtMobilePhone"
ErrorMessage="Mobile Phone is required." CssClass="error" ValidationGroup="vgStep2"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="cvMobilePerVal" runat="server" ClientValidationFunction="validateEmailOrMobilePerVal"
Display="Dynamic" ValidationGroup="vgStep2"></asp:CustomValidator>
<asp:Button ID="btnStep2Upper" runat="server" ClientIDMode="Static" OnClick="btnSaveContactClick" Text="Save" ValidationGroup="vgStep2" vg="vgStep2" OnClientClick="return ClientValidate();" />
Server Side Code
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{ /* I have put debugger here but control is not coming here*/
/* my validation logic*/
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{
if (txtMobilePhone.Text.Trim() != "")
{
RewardProgramDataContext db = new RewardProgramDataContext();
Boolean f = false;
string MobilePhone = cmnFunc.RemoveMobilePhoneFormat(txtMobilePhone.Text.Trim());
if (Request["id"] != null)
{
var cData = db.spContactSelectAllSingle(new Guid(Request["id"])).SingleOrDefault();
if (cData != null)
{
if (cmnFunc.RemoveMobilePhoneFormat(cData.MobilePhone) == MobilePhone)
{
f = true;
value.IsValid = true;
}
}
}
if (f == false)
{
var res = db.spContactDuplicateMobile(new Guid(ddlContactList.SelectedValue), MobilePhone).SingleOrDefault();
if (res.Column1 <= 0)
{
value.IsValid = true;
customIsValid = true;
}
else
{
value.IsValid = false;
customIsValid = false;
}
}
}
}
now when i click submit button all clent side validation working but serside custom validator is not calling

You forget to set the ControlToValidate property?
<asp:CustomValidator ID="cvMobilePhone" runat="server" ControlToValidate="txtMobilePhone" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" CssClass="error"></asp:CustomValidator>

You have a combination of two different things causing this behaviour.
Firstly, note that although—as has been said by others—you do not have to specify ControlToValidate, doing so restricts the circumstances in which the server-side custom validation event will fire. Specifically, if you leave it unset, the event always fires on postback, whereas if you set it, the event only fires when the control identified by ControlToValidate has a non-empty value.
Secondly, by specifying OnClientClick, you are telling the framework that you will take care of client-side validation, which will now not fire unless you call it from your OnClientClick function. Although you have not included your ClientValidate function in your question, I suspect you are not doing so, which leaves your RequiredFieldValidator powerless to prevent the postback.
In combination, these two things mean that
the postback occurs despite the empty textbox, and
the server-side custom validation does not fire on postback, because of the empty textbox.
You can call the client validation from your custom function using Page_ClientValidate()), which will be present in your page script since the page contains validators.
function ClientValidate() {
if (Page_ClientValidate()) {
//do custom validation, maybe return false
return true;
}
else {
return false;
}
}

Related

asp.net jscript Error: Unable to get property 'value' of undefined or null reference

Just start learning and having this problem while practicing with jscript
Code:
<script type="text/jscript" language="jscript">
function MyClientFunction(sender, arguments) {
var intValue = arguments.value;
alert(arguments.value);
if (intValue % 2 == 0) {
arguments.IsValue = true;
}
else {
alert("Use Even Numbers");
}
}
</script>
<asp:textbox ID="TextBox1" runat="server"></asp:textbox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="MyClientFunction();" EnableClientScript="true"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button"></asp:Button>
showing error after clicking the "button":
"...Error: Unable to get property 'value' of undefined or null reference..."
I'm not sure how the parameters are passed, not really familiar with how the jscript function works
tried this and no errors:
var intValue = document.getElementById("TextBox1").value;
alert(intValue);
Thanks a lot..
Don't pass this. You don't want to pass anything, you just want to give it the name of your function and the rest will be handled for you:
ClientValidationFunction="MyClientFunction"
Refer to the example on this page.
Also make sure you're using the correct capitalization. It should be arguments.Value and arguments.IsValid.
you have a few issues. here's a fixed version
<script>
function MyClientFunction(sender, args) {
var intValue = args.Value;
alert(args.Value);
if (intValue % 2 == 0) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Use Even Numbers"
ClientValidationFunction="MyClientFunction" EnableClientScript="true"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button"></asp:Button>
list of things changed
add ControlToValidate property on the validator, set the value to
the ID of the control you want it to validate - TextBox1 in this
case
the value for ClientValidationFunction should be only the name of a
javascript function, not an actual call to it
the function takes two arguments which you have right. I couldn't
find the definition for the parameter properties. the second
parameter has Value (with a capital V) which is the textbox input
now that you have associated the controls correctly.
set IsValid true or false within the method
move the error messages to the validator attribute rather than using
an alert
additionally I changed arguments to args since the former is a default name in javascript.
You aren't passing any parameters when calling your client function.
Therefore, both of its declared parameters are undefined.
You probably want to pass this as a parameter when you call it in the inline event handler.
The reason is because JavaScript is a Case Sensitive language.
The following code should work:
<script type="text/jscript" language="jscript">
function MyClientFunction(sender, arguments) {
var intValue = arguments.Value;
alert(arguments.Value);
if (intValue % 2 == 0) {
arguments.IsValue = true;
}
else {
alert("Use Even Numbers");
}
}
</script>
The explanation is that arguments is a parameter object that has two properties as you know (Value and IsValid) and you are referencing is property "Value" with lowercase "v".
Also you need to add the property ControlToValidate to your CustomValidator:
ControlToValidate="TextBox1"
the public ClientValidationFunction property of the CustomValidator just expect a valid full name reference to your function in your case you can use just "MyClientFunction" without the function call "();". Also all ASP.net validators have a public property called ValidationGroup that is just a label very handy if you have multiple validation regions.

set focus on custom validator

I have 2 textbox, one for login another for password.
I have 1 custom server side validator too, if password is entered wrong, validator is fired.
What I want is to set focus on this error message.
I have tried focus(), and setfocusonerror property too. but its not working.
here is my code:
<asp:CustomValidator ID="cvLogin"
runat="server"
Display="Dynamic"
CssClass="login-req"
OnServerValidate="cvLogin_ServerValidate"
ValidationGroup="tovalidate"
SetFocusOnError="True">
</asp:CustomValidator>
protected void cvLogin_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (currentUser == null)
{
args.IsValid = false;
MessageBox1.Focus();
MessageBox1.SetMessage(Resources.RSResource.Login_InvalidLogin,
Constants.MessageType.Error);
}
Try SetFocus method of Page:
if (currentUser == null)
{
args.IsValid = false;
Page.SetFocus(MessageBox1);
...
}
I am not sure. But may be you need to place your control on a Panel.
UPDATE 2:
I checked SetFocus method. It works for TextBoxes, but doesn't work for Labels or Validators. So if you want to set focus on message the best choise is using javascript:
document.getElementById('MessageBox1').scrollIntoView(true);
I also tested this server side code. It works fine:
Page.ClientScript.RegisterStartupScript(this.GetType(), "FocusScript", "document.getElementById('MessageBox1').scrollIntoView(true);", true);

Making a validator work from the back end code

I added a regex validator but its not showing anything on the page, basically the validation is done somewhere else i just needed to fire up. Here is the validator
<div>
<asp:RequiredFieldValidator
ID="RegularNoCardAccepted" runat="server"
ControlToValidate="txtCreditCardNumber"
CssClass="Error" Display="Dynamic">
</asp:RequiredFieldValidator>
</div>
And here is how I am trying to fire up, in reality i dont need it to check against a regular expression, I am just not sure how to make it pop up when it meets this condition
if (CardNotAccepted())
{
//Find the validator located somewhere in the master page.
RequiredFieldValidator reqVal =
FindControlRecursive(this.Page.Master, "RegularNoCardAccepted")
as RequiredFieldValidator;
if (reqVal != null)
{
//The code goes through here but it never shows.
reqVal.Enabled = true;
reqVal.Text = "Credit Card Type is not accepted";
reqVal.Visible = true;
reqVal.Validate();
}
return;
}
ASP.NET FieldValidators work automatically (assuming the Enabled property is set to true) on POST events. Here is an example of use: http://www.w3schools.com/aspnet/showasp.asp?filename=demo_reqfieldvalidator

Customer Validation ASP.Net C#

I am having the same problem as someone else in this forum. My validation control is not firing...and not sure where I have gone wrong. Could someone please take a look and let me know what obvious error I have here...thanks
I have set up a customer validator in my aspx page using the following:
<asp:TextBox ID="EmployeeNumber2TextBox" runat="server"
Text='<%# Bind("EmployeeNumber") %>'Visible='<%# AllowEmployeeNumberEdit() %>' />
<asp:CustomValidator ID="ValidateEmpNumber" runat="server"
onservervalidate="ValidateEmpNumber_ServerValidate"
controltovalidate="EmployeeNumber2TextBox"
ErrorMessage="You Must Enter an Employee Number" Text="*" />
and the code behind:
protected void ValidateEmpNumber_ServerValidate(object sender, System.Web.UI.WebControls.ServerValidateEventArgs e)
{
int SiteCompanyID = System.Convert.ToInt32(Session["SiteCompanyID"]);
SiteCompanyBLL SiteCompany = new SiteCompanyBLL();
SiteCompanyDAL.SiteCompanyRow ScRow = SiteCompany.GetCompanyByID(SiteCompanyID);
bool AutoGenerate = ScRow.AutoGenNumber; // result returning true or false
if (AutoGenerate == false)
{
if (e.Value.Length == 0)
e.IsValid = false;
else
e.IsValid = false;
}
}
Is the validator in sync with the control that is doing the submit/postback? Also, there is no condition that allows it to be true.
How do you know it isn't firing?
Did you try making the OnServerValidate and ControlToValidate with the first letter of each word uppercase? Those properties may be case sensitive.
I was able to run a cutdown version of your code on my system.
Are you sure your Web.config is set to compile debug?:
<compilation debug="true">

ASP.Net double-click problem

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>

Categories