Custom Validation not working in ASP.NET - asp.net

I need to have a custom validation for a "Save" operation in my page. The requirement is that, I need to display the alert and when I click the OK button in the alert, my page should not be posted back.
Here goes my code.
function RedirectForSaveValidation(source,arguments) {
var StatusFlag = '';
StatusFlag = document.getElementById('<%= HiddenStatusFlag.ClientID%>');
if (StatusFlag == "F") {
alert("Selected student entry has been qualified for lead. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "Q") {
alert("Selected student has been scheduled for interview/counselling. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "S") {
alert("Selected student entry has been scheduled with interview/counselling. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "I") {
alert("Selected student entry has been converted to Intake. Entry cannot be modified...!");
arguments.IsValid = false;
}
window.location.assign("EnquiryRegister.aspx");
}
I call this function in my button click.
<asp:Button ID="btnSaveEnquiryRegister" runat="server" Text="Save Enquiry Register" CssClass="button" OnClick="btnSaveEnquiryRegister_Click" ValidationGroup="valEnquiry" OnClientClick="RedirectForSaveValidation();"/>
The issue is, I am not getting any alert as I have specified and my page is posted back. What am I missing?

The correct way for solving this problem would be to use CustomValidator control and its ClientValidationFunction property. With this you can integrate your client side validation with ASP.NET validation functionality.
Have a look at the example on MSDN documentation.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx
Hope it helps!
Regards,
Uroš

Your are using a Custom Validation function directly on button click. Look you are passing two parameters in the Function and OnClientClick you are not passing parameters. this method should be called through CustomValidator control of asp.net.
Or just remove parameters from method. Use method without parameters

well this is not the correct way to implement the custom validator look at this http://www.w3schools.com/aspnet/control_customvalidator.asp and http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_customvalidator (show you how to do it properly)
but still if you want to do the validation like this you have to return false in case it is not valid
so your validation function should return true (in case it is valid) or false
then
<asp:Button ID="btnSaveEnquiryRegister" runat="server" Text="Save Enquiry Register" CssClass="button" OnClick="btnSaveEnquiryRegister_Click" ValidationGroup="valEnquiry" OnClientClick="return RedirectForSaveValidation();"/>

Silly me! The issue was with getting the value of my hidden field.
var StatusFlag = '';
StatusFlag = document.getElementById('<%= HiddenStatusFlag.ClientID%>').value;
I had missed to include value property so the variable had empty value which caused the validator to fail.

Related

how to check if validationgroup passed?

Currently working with UserControls.
Have this button :
<dx:ASPxButton ID="btnSave" runat="server" Text="Save" CssClass="btn btn-active" ValidationGroup="MyValidationGroup" OnClick="BtnSaveClick">
I inherited this code from my team mates.
Recently i discovered that if button is clicked multiple times, it duplicates the record.
I tried to add
btnSave.ClientEnabled = false;
and
btnSave.Enabled = false;
into the code behind, but it's not preventing from duplicating the records.
How to check if validation group passed (successfully) into jquery or javascript, than disable the button on the front end ?
Any idea ?
well simply use
<asp:Button ID="btnSave" runat="server" class="btn btn-active" OnClick="btnSave_Click" ValidationGroup="validation" Text="Save" OnClientClick="if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';"
UseSubmitBehavior="false" />
This code snippet will disable your button and doesn't allow use to click multiple times until click event executing its code
Hope this will help :)
If you do not want duplicates, why not check them at the database level? Disabling a button will help with double clicking. But you will still get the same result if a user presses F5 or reloads the page as new and then presses the button again.
For MS SQL you could do something like this:
IF NOT EXISTS (SELECT column FROM table WHERE (column = #myVar))
INSERT INTO table (column) VALUES (#myVar)
Or you could also place a constraint on the column
ALTER TABLE table ADD CONSTRAINT UQ_column UNIQUE (column)
you can do this $(document).ready(function(){
$('#ctl00_MainContent_btnSave')
.attr("onclick", null)
.removeAttr("onclick")
.click(function() {
// To validate you form using Validation group.
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate("ValidationGroup");
if (Page_IsValid == true) {
alert('the form is valid');
}
} else {
if ($(this).valid()) {
alert('the form is valid');
}
}
//Disable button before page posting back
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
});
});
I figured it out. When i used code #Shayan Hafeez provided, compiler thrown an exception.
The server tag is not well formed.
Than, i removed OnClientClick from the button and insert this code into code-behind :
btnSave.ClientSideEvents.Click = "if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';";
It works fine now.

customvalidator for client side validation not working

We have a form used by a number of our customers where someone can register on their web site. It's customizable in that the owner of the form can set a field to be shown or hidden on the form and also required. However, some fields if shown, require that another field be set for the form to be valid. So the validation can be tricky. The other tricky part is that we wanted all the error messages to show together in the validation summary. If I simply had my own function that was called onclientclick for the linkbutton I couldn't add any error messages it generated to the validation summary.
So the solution that we found originally was creating a custom validator on the page without setting it's controltovalidate property but leaving it's clientvalidationfunction set to the function we wanted to call. This allowed us to set the errormessage of the sender argument so that it then showed up in the validationsummary.
We needed to add some additional validation logic and when doing this I realized that the page no longer works as it used to (I think it was working back in .net 2, now we're on .net 4).
Here's the basic html code I have.
Web page -
<asp:ValidationSummary ID="vsummary" runat="server" HeaderText="Oops, it appears the following required fields are not completed." CssClass="error" />
<asp:CustomValidator ID="cstCustomScripts" runat="server" ClientValidationFunction="ValidateExtraFields" />
...additional form fields here
<asp:LinkButton ID="btnAddUpdate" runat="server" onclick="SubmitProfile" />
And the javascript that gets called by the custom validator...
function ValidateExtraFields(sender, args) {
args.IsValid = true;
if (typeof window.RelocationSelectionRequired == 'function') {
if (!RelocationSelectionRequired()){
args.IsValid = false;
sender.errormessage = "If you are open to relocating, please select the state(s) and cities.";
return;
}
}
if (typeof window.ValidateHomeState == 'function') {
if (!ValidateHomeState()) {
args.IsValid = false;
sender.errormessage = "Home state is required.";
return;
}
}
if (typeof window.ValidateWorkState == 'function') {
if (!ValidateWorkState()) {
args.IsValid = false;
sender.errormessage = "Work state is required.";
return;
}
}
var invalidNumberField = "";
$("[data-validate-function='GreaterThanZero']").each(function () {
var t = $(this);
if (t.val().trim() == "0") {
args.IsValid = false;
invalidNumberField = t.attr("controlName");
return false;
}
});
if (invalidNumberField.length > 0) {
sender.errormessage = invalidNumberField + " cannot be zero.";
return;
}
}
In the past the function would successfully append any messages from this function to the validationsummary control and not submit the form. Now it still appends the message but the form also submits when it shouldn't. Does anyone know if this is a result of moving from .net 2 to .net 4? Or is there some other reason it no longer works? Thanks.
Your link button should have CauseValidation = true for the validation to be fired.
You said that you beleive this worked in .net 2.0. I found a page about Breaking changes in ASP.NET 4. I don't see anything specific about the CustomValidator Control that would be a breaking change. But it speaks of a setting in web.config that you can use try. It will lower the Rendering Compatability Version to 2.0 or 3.5.
<pages controlRenderingCompatibilityVersion="2.0" />
or
<pages controlRenderingCompatibilityVersion="3.5" />
If that don't work you can also try to lower the .net version of the web project to 2.0 or 3.5.

Making ASP label visible in Javascript?

This is my label I want to display if the user have left out field before clicking the button. What am I doing wrong because nothing is happening when I click the button.
<asp:Label ID="lblError" runat="server"
Text="* Please complete all mandatory fields" style="display: none;" >
</asp:Label>
This is the function I call when I click on the button:
function valSubmit(){
varName = document.form1.txtName.value;
varSurname = document.form1.txtSurname.value;
if (varName == "" || varSurname == "")
{
document.getElementById('lblError').style.display = 'inherit';
}
else
{
.................other code go here...........................
return true;
}
}
Why not use the Validation controls? These will give you client and server side validation out of the box - not that I'm lazy or anything... ;-)
Edit for comment:
The RequiredFieldValidator can be set to display a single red asterisk by the side of each control, and a validation summary control could be used BUT that would take up space.
So, it's possible that ASP.Net is renaming your control, so your JS should read:
document.getElementById('<%= lblError.ClientID %>').style.display = 'inherit';
Give that a go...
Personally, I'd still use the Validator controls ;-)
You shouldn't be using lblError as an ID in JavaScript code. Instead you should use:
'<%= lblError.ClientID %>'
Of course this is only possible if you are generating the JavaScript code in the ASP.NET file.
on your desired event use this
document.getElementById('<%= lblError.ClientID %>').style.display = ""; or
document.getElementById('<%= lblError.ClientID %>').style.display = "block"
ok then try this, instead of client side, make it serverside. First set it invisible like , on formload event set invisible using lblEror.visible = false and remove style ="display:none" from html.
Then on the desired event/s make it visible and after processing again invisible.
If you want it strictly thorugh js.try this workaround. remove style from asp label. on body onload make it disable from some js function. now on the btn click event make it visible using the method something like this
function Validate()
{
var objLbl = $get('<%=lblError.ClientID%>');
if (validations fails)
{
objLbl.style.display = ""; //displays label
return false;
}
else
{
objLbl.style.display="none" //hides label
return true;
}
}
<asp:button id="btnValidate" runat="server" onclientclick="return validate();"/>
Hope this will work
Take a look at jquery, you can select by classes instead of id's which will never be altered when rendered onto the page (unlike id's)

How to set Page.IsValid in ASP.Net

When the page class property IsValid is read only, how can I set it using my own validation method?
So far all I've been able to do is set this property by calling Page.Validate().
How can I write my own functionality that will change the IsValid property just like Page.Validate()?
You don't set IsValid directly instead you call Validate() method of the Page object. If you have your custom validation methods then you need to use CustomValidator object and set that function in its server side validation property.
<asp:CustomValidator ID="YourValidator" runat="server" SetFocusOnError="true"
ControlToValidate="YourControl"
ClientValidationFunction="YOUR_JAVASCRIPT_FUNCTION"
OnServerValidate="YOUR_SERVER_VALIDATION_FUNCTION" Text="*" />
I know this is old, but, I needed to do something similar, basically forcing the IsValid property to false (don't ask why). Here is what I did basically (what you see here is my proof of concept):
Added this to the .aspx page:
<asp:TextBox ID="txtDummy" runat="server" Visible="false" />
<asp:RangeValidator ID="rvDummy" ControlToValidate="txtDummy" runat="server" MinimumValue="1" MaximumValue="2" />
And then I added this to the code behind:
bool makeMyPageInvalid = true;
if (makeMyPageInvalid)
txtDummy.Text = "0";
Page.Validate();
if (Page.IsValid)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('valid');", true);
else
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('not valid');", true);
You can see that this only allows you to force the page validation to an invalid state. You can use any validator or reason to set this. Hope this helps someone!
The IsValid property is read-only because it is intended for use with server and client-side validators like the RequiredFieldValidator and RegularExpressionValidator. It's read-only because you can't force a page to be valid programmatically. "Valid" in this context means all the validators on the page evaluate to true.
If you feel like using some JavaScript you can do it in the client-side by modifying the variable Page_IsValid like this:
function pageLoad() {
Page_IsValid = false;
}
I use this just in case someone clicks the submit button w/o entering data. Then I can display an alert like this:
function valid() {
if (!Page_IsValid) {
alert("Some Questions Remain Unanswered and are Marked with a Red Asterisc. ( * )");
}
(at the beginning I thought 'who would submit a form w/o data' but sooner rather than later I realized it happens)
This is a really old question, but it came up in a search so I thought I'd add my answer to it. First, create an extension method in one of your helper classes.
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
Now in your code behind file, loop over every validator on the page that is not validating.
foreach (var validator in Page.GetAllControlsOfType<BaseValidator>().Where(w => !w.IsValid))
{
validator.IsValid = true;
}

TextBox causes Button Postback in ASP.NET

ASP.NET 2.0, testing in FF3 and IE7.
When I hit the 'enter' button from a text box the corresponding "OnClick" event for the first ImageButton in the page is fired. If I remove that image button, it fires the next ImageButton OnClick event on the page.
From the FireBug console, if I use JavaScript to submit the Form, this does not happen. But for whatever reason hitting enter from the textbox triggers the unrelated ImageButton event.
I found this question which had a similar problem, however the proposed answer to that solution doesn't work since ImageButtons do not have a "UseSubmitBehavior" property on them.
I don't understand why this event is firing. If I look at Request.Form, I can see that __EVENTTARGET is empty, and it is in fact posting the entire form contents (all of my textboxes), but also includes imageButton.x and imageButton.y key/value pairs.
Why is this? I suppose I could detect "enter" key presses from these text boxes with javascript, but my experience in the past is this behavior is highly variable between browsers. Any suggestions?
here's a more elegant solution
<asp:TextBox ID="TextBox1" runat="server"
onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>
read the entire post here
You could try setting a default button in an asp panel or on your form. This will let you control what happens when a user hits the enter key.
I'm having the same issue on my project.
This issue is caused because ASP.NET always will assume that the first element that inherits from IButton interface (Button and ImageButton) is the default button from the page.
Hipoteticaly, if you use an LinkButton instead of Button or ImageButton, this issue is solved.
You can find more information here on MSDN.
You can disable the Enter key from being pressed, so the user will have to click on of your ImageButtons. Just paste this javascript block onto your page:
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Recently, I've been doing more on the client with web services and fewer postbacks. By moving my controls outside of the form element (or eliminating it altogether), the problem goes away. It's inserted by default on aspx pages, but it didn't occur to me until recently that I don't need it for much of what I do.
Its the default behaviour for an enter button press in a non text area to post back a form. You would have to handle it in a javascript method to stop the postback.
You'd just need to check the window.event.keyCode property to see if its equal to 13. If it is, reset it to 0.
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode = 0;
}
}
I suppose I could detect "enter" key presses from these text boxes with javascript
That's what I did to get around that behaviour and it works great in IE7 and FF3. It's just a little unnatural.
Here is a generic exemple:
function TextBox1_KeyDown(sender, e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13 && $("#TextBox1").val() != "")
{
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("TextBox1", "", true, "", "", false, true));
}
return (key != 13);
}
I used WebForm_DoPostBackWithOptions because I needed validators to trigger. Otherwise, you might want to use __DoPostBack.
Here are the "prototypes":
function __doPostBack(eventTarget, eventArgument)
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)
{
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options)
Hope it helps.
P.S.: I used JQuery here but $get would be the same.
Here's an elegant solution I have found, in case anybody else has this problem (in case all other solution don't work for you, as they didn't work for me):
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Panel runat="server" DefaultButton="doNothingButton">
<ul id="shopping-list-ul">
</ul>
<asp:Button CssClass="invisible" runat="server" ID="doNothingButton" OnClientClick="return false;" />
</asp:Panel>
</ContentTemplate>
The textbox iself was inside the ul (generated by javascript).
Pressing enter will trigger the "doNothingButton", which will return false on client side, causing no postback at all!

Resources