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.
Related
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
}
}
I have a Validate method that looks like this
protected void ValidateHello(Object sender, ServerValidateEventArgs args)
{
//Validate Stuff
}
In my ASP I have this line to validate a drop down list.
<asp:CustomValidator ID="cvNames" runat="server" ControlToValidate="ddlNames" OnServerValidate="ValidateHello" Display="Dynamic" ErrorMessage="Please select a Name">*</asp:CustomValidator>
However I have 2 different imagebuttons. One should have different validation for this drop down box than the other. The only way I can think about doing this is to have an if() statement and check which imagebutton was pressed to cause the validation.
Here is my ImageButton code.
<asp:ImageButton runat="server" ID="imgSearchNames" CssClass="SearchButton" ImageUrl="~/Images/searchbutton.jpg" OnClick="imgSearchNames_OnClick" ></asp:ImageButton>
And this is my OnClick event method.
protected void imgSearchNames_OnClick(Object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
//Do Stuff
}
}
Much help is needed and thanks in advance.
Why don't you use validationGroup.
ValidationGroup property makes your inputs to validate only for particular events( imagebutton_click let's say) ,
<asp:ImageButton ID="imgBtn" ValidationGroup="xxxx" CausesValidation="true" />
<asp:CustomValidator ID="cvNames" runat="server" ValidationGroup="xxxx" OnServerValidate="ValidateHello" Display="Dynamic" ErrorMessage="Please select a Name">*</asp:CustomValidator>
Use same ValidationGroup in your Imagebutton .
You should also consider using ValidateEmptyText=true so that your it will fire validation even for empty controls .
I know there are a lot of threads about this error, but I've looked through all of them and haven't been able to make it work. It's probably something very small that I am overlooking.
This is the code I have now, in an asp:Button component
<asp:Button ID="btn_profile" runat="server" Text="Bekijk de wenslijst"
CssClass="wenslijst_preview_btn"
OnClick="btn_goToChild_Click(<%# Eval("pk_child_id") %>)"/>
I have tried multiple things, for example the following:
OnClick='btn_goToChild_Click(<%# Eval("pk_child_id") %>)'
But then I get the following error:
preprocessor directives must appear as the first non-whitespace character on a line
If you need to see more code, let me know!
OnClick is a server-side event, so should just be the name of a server-side event handler. OnClientClick (where available) is a client-side event handler, so would take a JavaScript expression to evaluate.
Try
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick='btn_goToChild_Click(<%# Eval("pk_child_id") %>)' />
<asp:Button ID="btn_profile" runat="server" Text="Bekijk de wenslijst"
CssClass="wenslijst_preview_btn" CommandArgument='<%# Eval("pk_child_id") %>'
OnClick="btn_goToChild_Click"/>
protected void btn_goToChild_Click(object sender, EventArgs e)
{
Button btn= (Button) sender;
if (btn==null) return;
var id =btn.CommandArgument;
// Or int id=(int)btn.CommandArgument;
}
If you want to use Javascript expression, use OnClientClick not OnClick. These are different side events.
OnClick is used for server side methods only, for client side calls you should use "OnClientClick" attribute.
I have to validate that the year entered must be less than or equals to the current year. I am using server side validators in ASP.Net and C#, and all validators are inside a validator group. So please suggest me to validate one more condition within the same.
Thanks
Amit Ranjan.
Use the ASP.NET CompareValidator.
For e.g. if you have a TextBox with id TextBox1, which accepts a year in 'yyyy' format, then you can do the following:
Year:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server"
Operator="LessThan" ControlToValidate="TextBox1" ErrorMessage="Year must
be less than current year" Type="Integer"></asp:CompareValidator>
Add this to code behind:
protected void Page_Load(object sender, EventArgs e)
{
CompareValidator1.ValueToCompare = DateTime.Today.Year;
}
Also remember using validators won't stop a Submit; use these in conjunction with ValidationSummary Control.
More on MSDN: http://msdn.microsoft.com/en-us/library/f9h59855(v=vs.80).aspx
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!