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.
Related
I have a FileUpload control to upload a certificate file. The user has to upload the file the first time, in subsequent visits to the page, we display the certificate content on the page, so it's not necessary to upload a file again.
Now I want to validate that a certificate is uploaded at least at once. The rest of the page uses ASP.NET validation controls so I want to go ahead with the same.
I can't use a RequiredFieldValidator on the FileUpload, because then it will fire everytime I try to save the page, which is wrong.
I tried using a CustomValidator and used the serverside validation, but seems that too fires only if I click on the file uploader. If I just leave it alone, the server side validation is not triggered.
I can of course do the validation on the [Save] button click event, but is there a proper way to do that using the validator events themselves?
CustomValidator:
<asp:CustomValidator ID="cusCertifacteExistanceValidator" runat="server" ValidationGroup="ConfigValidation" CssClass="errorMsg" ControlToValidate="fcertificate" Enabled="false" ErrorMessage="Certificate is not available" OnServerValidate="ValidateCertificateUpload">*</asp:CustomValidator>
CustomValidator Server side validation:
protected void ValidateCertificateUpload(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
var existingCertificate = string.Empty;
if (ViewState["loginProviderProperties"] != null)
{
existingCertificate = ((List<Configuration>)ViewState["properties"]).Find(p => p.Name == "certificate").Value;
}
if (fX509Certificate.HasFile || existingCertificate != string.Empty)
{
args.IsValid = true;
}
}
It is very dificult to imagine without the code but My guess would be to add
ValidateEmptyText="true"
to custom validator.
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.
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.
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;
}
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!