This has not happened to me before, but for some reason both the client and server side validation events are not being triggered:
<asp:TextBox ID="TextBoxDTownCity" runat="server" CssClass="contactfield" />
<asp:CustomValidator ID="CustomValidator2" runat="server" EnableClientScript="true"
ErrorMessage="Delivery Town or City required"
ClientValidationFunction="TextBoxDTownCityClient"
ControlToValidate="TextBoxDTownCity"
OnServerValidate="TextBoxDTownCity_Validate" Display="Dynamic" >
</asp:CustomValidator>
Server-side validation event:
protected void TextBoxDTownCity_Validate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Client-side validation event:
function TextBoxDCountyClient(sender, args) {
args.IsValid = false;
alert("test");
}
I thought at the least the Server Side validation would fire but no. this has never happened to me before. This has really got me stumped.
I looked at the output and ASP.NET is recognizing the client side function:
ASP.NET JavaScript output:
var ctl00_ctl00_content_content_CustomValidator2 = document.all ? document.all["ctl00_ctl00_content_content_CustomValidator2"] : document.getElementById("ctl00_ctl00_content_content_CustomValidator2");
ctl00_ctl00_content_content_CustomValidator2.controltovalidate = "ctl00_ctl00_content_content_TextBoxDTownCity";
ctl00_ctl00_content_content_CustomValidator2.errormessage = "Delivery Town or City required";
ctl00_ctl00_content_content_CustomValidator2.display = "Dynamic";
ctl00_ctl00_content_content_CustomValidator2.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_ctl00_content_content_CustomValidator2.clientvalidationfunction = "TextBoxDTownCityClient";
Rendered custom validator:
<span id="ctl00_ctl00_content_content_CustomValidator2" style="color:Red;display:none;">Delivery Town or City required</span>
Can any one shed some light as to why both client and server side validation would not be firing.
Edit: Typo I pasted in the wrong function, problem still the same
Just another update to the last comment: where by the TextBox cannot be empty. I tested this out and it is not true. On a blank page the CustomValidator fired my client side validation function fine without a value:
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="CustomValidator" ClientValidationFunction="TextBoxDAddress1Client"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Use this:
<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>
To validate an empty field.
You don't need to add 2 validators !
Your CustomValidator will only fire when the TextBox isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.
Note: If the input control is empty,
no validation functions are called and
validation succeeds. Use a
RequiredFieldValidator control to
require the user to enter data in the
input control.
EDIT:
If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.
So you can't do this...
<script>
function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />
But this works:
<script>
function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />
I'm guessing it conflicts with internal .NET Javascript?
Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via
Page.Validate({Insert validation group name here});
Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?
I'm not sure what else might cause this behavior.
Server-side validation won't fire if client-side validation is invalid, the postback is not send.
Don't you have some other validation that doesn't pass?
The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be
TextBoxDAddress1Client
(as you wrote)
Thanks for that info on the ControlToValidate LukeH!
What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.
Cheers!
Related
I am constantly getting incorrect info from the "Instructor" at school on this.
For ASP.NET Web Applications, the Validators from the Toolbox like CompareValidator, RangeValidator, RequiredFieldValidator, etc, are those considered Server-Side Validation?
Because we also add a jQuery NuGet package and it gives real time validation when the user tabs, like if the user types a letter when a number is required.
For WPF's in C# I create a Validator Class or use a Library and check validation that way through Static Methods. Should I be doing it this way in ASP.NET as well? Or are the RequiredFieldValidators, etc enough for Server-Side Validation?
Here is an example:
<div class="form-group">
<label class="control-label col-sm-4">Length:</label>
<div class="col-sm-4">
<asp:TextBox ID="txtLength" runat="server" CssClass="form-control" MaxLength="15"></asp:TextBox>
</div>
<div class="col-sm-4">
<asp:RequiredFieldValidator ID="rfvLength" runat="server" ErrorMessage="Length is required"
ControlToValidate="txtLength" CssClass="error" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="rngLength" runat="server" ErrorMessage="Must be between .01 and 10,000"
MaximumValue="10000" MinimumValue=".01" ControlToValidate="txtLength" CssClass="error" Display="Dynamic"
SetFocusOnError="True" Type="Double"></asp:RangeValidator>
</div>
</div>
thanks
******EDIT*****
Guys you are giving unclear or incomplete answers just like my "Instructor" does.
Yes or No please, is this Server-side Validation in ASP.NET?
<div class="form-group">
<label class="control-label col-sm-4">Length:</label>
<div class="col-sm-4">
<asp:TextBox ID="txtLength" runat="server" CssClass="form-control" MaxLength="15"></asp:TextBox>
</div>
<div class="col-sm-4">
<asp:RequiredFieldValidator ID="rfvLength" runat="server" ErrorMessage="Length is required"
ControlToValidate="txtLength" CssClass="error" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="rngLength" runat="server" ErrorMessage="Must be between .01 and 10,000"
MaximumValue="10000" MinimumValue=".01" ControlToValidate="txtLength" CssClass="error" Display="Dynamic"
SetFocusOnError="True" Type="Double"></asp:RangeValidator>
</div>
</div>
and then I also add:
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValid)
{
double length = Convert.ToDouble(txtLength.Text);
double width = Convert.ToDouble(txtWidth.Text);
Rectangle r = new Rectangle(length, width);
txtArea.Text = r.Area().ToString("f");
txtPerimeter.Text = r.Perimeter().ToString("f");
txtDiagonal.Text = r.Diagonal().ToString("f");
}
}
Is this correct as Server-side Validation in ASP.NET and am I using the if (IsValid) part correctly?
You are mixing ASP.NET Validation Control and difference between Client side and Server Side validation.
When ASP.NET page renders the Validation Controls RequiredFieldValidator and RangeValidator etc., it automatically creates Client side JavaScript function to perform validation within the browser i.e. client side validation.
IsValid is server side validation feature of ASP.Net Pages by which it verifies whether the Asp.Net Validation Control used in the WebForm/ WebPage had performed the validation, and at the server side code, if all the validation is applied (i.e. if all mandatory fields etc. are entered ) then IsValid becomes true.
Note that is not mandatory to put IsValid in server side code, as the JavaScript functions which are created will do the required validations on the client side.
So, basically ASP.NET Validation Control helps to validate ASP.NET pages from both Client Side and Server Side, and have an advantage compared to plain JavaScript validation.
Another example is JQuery code (JavaScript Library) which can be used to do Client Side validation like validating if textbox's value is empty or not. At the same time JQuery can be used to do server side validation by an AJAX call to a web service method on the server side.
When using the ASP.Net validation server-controls, you still want to double-check that that Page.IsValid before attempting to save the data on the server-side.
According to MSDN, those controls inject some kind of javascript validation at client-side;
By default, the validator controls inject client-side ECMAScript (JavaScript) into the page to perform validation checking in the browser. This gives users instant feedback on validation errors; without the client script, checking for validation errors would require a round trip to the server, which could be slow at times. In fact, you cannot submit the page until the client-side validation succeeds
https://msdn.microsoft.com/en-us/library/a0z2h4sw.aspx
Some controls also have a server validation option, which you can use if you need to:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
try
{
DateTime.ParseExact(args.Value, "m/d/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo);
args.IsValid = true;
}
catch
{
args.IsValid = false;
}}
You can also check for Page.IsValid
ASP.NET Validation controls can be used in both client and server-side validation. Validation controls always perform validation on the server. They also have complete client-side implementation.
Use the EnableClientScript property to specify whether client-side validation is enabled.
I have a widget for a newsletter in which i use the RegularExpressionValidator to check if the email input is valid. My codebehind is a method that opens an smtp connection and sends an email.
My .aspx looks like this:
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control newsmail"></asp:TextBox>
<asp:RegularExpressionValidator style="position:absolute; margin-top:50px; margin-left:58px;" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid E-mail" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:Button ID="submit" runat="server" Text="Submit" CssClass="btn btn-lg btn-success submit" OnClick="submit_Click1" />
and my codebehind has the following method:
protected void submit_Click1(object sender, EventArgs e)
{
....
}
Obviously as it is now, it will try to send the email whether the e-mail is valid or not. Therefore im looking for some kind of conditional expression that takes the RegEx into consideration before it completes the method and sends the e-mail.
I know its possible to do it all in C#, but im fairly new to C#, so this looked like the easiest workaround at this point.
The validators in the ASP.net page can already work as JavaScript in the Browser. When you enable this functionality and the user's browser has JavaScript enabled, then your submit_Click1 method will not even be executed when there is invalid data in the input controls.
If you disable the validators to work at the client side or the user's browser does not have JavaScript enabled, you should check in the code behind that all the validators successfully validated the user input. You can do that by checking the isValid property of the page:
protected void submit_Click1(object sender, EventArgs e)
{
if(Page.IsValid)
{
// All Validators Passed -> Do something
}
else
{
// Some invalid data, do nothing
}
}
Client side validation works fine. I disabled the client side to see if it also works good server side, but fails. The compiler reaches 'SaveData' even if the input text is invalid.
There are no update panels.
How should I solve this.
ASPX:
<asp:TextBox ID="txtDept" runat="server" pattern="[a-z A-Z]*"></asp:TextBox>
<asp:RegularExpressionValidator
ID="revDept"
runat="server"
ValidationExpression="^[a-zA-Z\s]{1,50}$"
ControlToValidate="txtDept"
Display="Dynamic"
ErrorMessage="Only alphabets and spaces are allowed."
EnableClientScript="false">
</asp:RegularExpressionValidator>
C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SaveData();
}
}
You need to either have "CausesValidation" enabled on the submit button (we can't check in your code if it is so), or to call explicitly "Page.Validate()" before to test the IsValid property.
Please also take a look at How does Page.IsValid work? , it could be helful.
I tried creating a custom validator to validate a checkbox and got this error:
"Control 'cbVerify' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated."
Here is the front end code i have for this:
<li>
<asp:CheckBox ID="cbVerify" runat="server" Text="I certify that the information entered on this form is correct and accurate." />
</li>
<li>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please check" Display="Dynamic" ControlToValidate="cbVerify" OnServerValidate="CustomValidator1_ServerValidate" CssClass="ValidationError"></asp:CustomValidator>
</li>
Back end:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = cbVerify.Checked ;
}
Could i get some help figuring this out?
Remove the ControlTovalidate value from CustomValidator1. it does not need to be there for checkboxes.
MSDN reference
Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. The ID must refer to a control within the same container as the validation control. It must be in the same page or user control, or it must be in the same template of a templated control.
The standard controls that can be validated are:
System.Web.UI.WebControls.DropDownList
System.Web.UI.WebControls.FileUpload
System.Web.UI.WebControls.ListBox
System.Web.UI.WebControls.RadioButtonList
System.Web.UI.WebControls.TextBox
System.Web.UI.HtmlControls.HtmlInputFile
System.Web.UI.HtmlControls.HtmlInputPassword
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlSelect
System.Web.UI.HtmlControls.HtmlTextArea
You don't need to set ControlToValidate property for CustomValidator when using it with CheckBox and simply use this in Server Validate like:
args.IsValid = cbVerify.Checked;
I have a button that, when an user clicks on it and some fields are not correct, a message will be displayed. I would like to make that validation with javascript(or maybe someday I will), but I have no idea how to make that. Currently when the user clicks the button, the onclick function on the server side wont be executed.
Just use <asp:Validator tags; there are a number of different types of validators such as required field validators regex validators, etc.
They will validate the data both in client side code as well as server side code (unless you disable the client side check, which you can do).
This is much easier than manually validating the content in javascript and also manually validating it in server side code.
Technically though, to answer your question, when you have an onclick javascript handler for a submit button the return value, as a boolean, indicates whether or not the form should be submitted, so you just need to return false if the data is not valid to not submit the form.
<asp:Button Text="Submit" OnClientClick="return Validate();" />
<script type="text/Javascript">
function Validate()
{
if(requiredFieldAIsMissing) return false;
return true;
}
</script>
How about:
<asp:Button ID="myButton" Text="Click Me!" OnClick="myButton_OnClick" OnClientClick="javascript:confirm('Really?')" />
The OnClientClick property emits the javascript (ahead of the javascript required to handle the postback), and if you return false from that event the rest of the event is cancelled and the postback will not fire.
I think something like below would help you to understand.
HTML:
<asp:textbox id="myText" runat="server" text="Hello" />
<asp:button id="myButton" runat="server" text="Click Me" OnClick="Server_Event" />
ON Page_Load:
//Add onclick with return here
myButton.Attributes.Add("onclick","return ButtonClicked()");
Javascript:
function ButtonClicked(){
var txt = document.getElementById("myText");
if(txt.value != "Hello"){
alert("It is not Hello, I am NOT posting back!");
return false;
} else {
alert("It is Hello, I am posting back!");
return true;
}
}