Custom Validation doesn't fire - c#

Here are my lines of code:
For the Textbox and the CustomValidator:
<asp:TextBox ID="Edit_Tbox_Email" runat="server" placeholder="Email Address..." CausesValidation="true" ValidationGroup="submission"></asp:TextBox>
<asp:CustomValidator runat="server" ControlToValidate="Edit_Tbox_Email" ID="cv_Email" OnServerValidate="cv_Email_ServerValidate" ErrorMessage="!" data-toggle="tooltip" title="Invalid Input!" ValidationGroup="submission"></asp:CustomValidator>
This is for the Button to allow the user to change his/her email:
<asp:Button ID="Edit_But_Email" runat="server" Text="Change" CssClass="btn btn-small" OnClick="Edit_But_Email_Click" ValidationGroup="submission" CausesValidation="true"/>
On server side:
protected void Edit_But_Email_Click(object sender, EventArgs e)
{
if(Page.IsValid)
Edit_Lab_Email.Text = Edit_Tbox_Email.Text;
}
protected void cv_Email_ServerValidate(object source, ServerValidateEventArgs args)
{
string emailRegex = "^\\w+[\\w-\\.]*\\#\\w+((-\\w+)|(\\w*))\\.[a-z]{2,3}$";
if (Edit_Tbox_Email.Text.Length == 0 || Regex.IsMatch(Edit_Tbox_Email.Text, emailRegex))
{
cv_Email.IsValid = false;
}
}
But the problem here is that cv_Email_ServerValidate() doesn't even fire. Basically, it doesn't validate the Textbox. Also, I don't want to use the RequiredFieldValidator and RegularExpressionValidator. I want to combine their functionalities into just one validator. And as much as possible I would like to use the code behind(c#) only and not by jQuery. Thank You!

Your button have a ValidationGroup but your CustomValidator don't have one. If you want your button to valide it, you must set the same ValidationGroup.
Edit:
You have to set ValidateEmptyText="true" otherwise, it won't validate empty value.

Related

Setting ValidationGroup on RequiredFieldValidator from a property isn't setting correctly

I am trying to set my required field validators ValidationGroup dynamically from a property on my page however they are not firing. If I set the string manually it fires. My assumption is that its not pulling the property properly into the ValidationGroup. Am I missing something?
<asp:RequiredFieldValidator runat="server" ID="rfvHouseName" ControlToValidate="txtHouseName" ErrorMessage="Please enter a house name/no." ForeColor="Red" ValidationGroup="<%#ValidationGroup%>"><i class="fa fa-star requiredFieldStar"></i></asp:RequiredFieldValidator>
<asp:TextBox ID="txtHouseName" runat="server" MaxLength="50" CssClass="form-control" />
private static string _validationGroup = "NewAddress";
public virtual string ValidationGroup
{
get { return _validationGroup; }
set { _validationGroup = value; }
}
You have to set it in code behind
rfvHouseName.ValidationGroup = ValidationGroup;
Or if you really want to use it inline, you have to use it like this
<asp:RequiredFieldValidator ValidationGroup='<%# ValidationGroup %>'
However for the second one to work you have to call DataBind() from code behind every time.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}

Button Click fires before custom validation occurs

I have this form with a custom validator, and Button.
But, my custom Validator shows error only after button click.
This is my validator, Button and code behind.
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="User Name cannot be Empty!" ForeColor="Red"
onservervalidate="CustomValidator1_ServerValidate"
ControlToValidate="userNameTxt" ValidateEmptyText="True"
ValidationGroup="save-valid"></asp:CustomValidator>
<asp:Button ID="saveButton" runat="server" Text="Save" CssClass="save-button"
onclick="saveButton_Click" TabIndex="7" ValidationGroup="save-valid" />
This is my code behind.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsUserValid(userNameTxt.Text))
{
CustomValidator1.ErrorMessage = "User Name cannot be Empty!";
args.IsValid = false;
}
else
args.IsValid = true;
}
protected void saveButton_Click(object sender, EventArgs e)
{
//This code executes regardless of CUstom Validator
}
You can try to use client side validation.
<script type="text/jscript">
function textBoxControl(source,arguments){
if(arguments.Value.length >0) //or control things (e.g. at least 6 character)
arguments.isValid = true;
else
arguments.isValid = false;
}
<script>
Code behind is like below.
<asp:TextBox ID="userNameTxt" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator"
onservervalidate="CustomValidator1_ServerValidate"
ControlToValidate="userNameTxt"
ClientValidationFunction="textBoxControl"></asp:CustomValidator>
When I put the below code inside Save Button click, the problem gets solved.
if (!Page.IsValid)
return;

Update panel with textbox values when button clicked

I am still learning the basics of C# so any help would be appreciated. I have a series of asp:TextBox's. In the code behind, I am getting the value of these boxes. Is there a way to have a panel hidden until a user clicks submit then have the values display?
Here is the HTML for one of the boxes and the panel:
<asp:TextBox ID="txtTitle" runat="server></asp:TextBox>
<asp:Panel ID="PDFPanel" runat="server"></asp:Panel>
The button:
<asp:Button ID="btn_Submit" runat="server" Text="Button" OnClick="btnSubmit"/>
and the code-behind for it:
string Title = txtTitle.Text;
public void btnSubmit(Object sender, EventArgs e)
{
}
There are about 50 fields, so I am not showing all of it but if I can get direction on one I can replicate for the rest. Please let me know if I need to show any additional code
I am sorry if this is simple, but like I said, I am still an entry level developer. Thanks in advance!
Unless I've misunderstood what you're asking, this should be fairly simple.
<asp:Panel ID="PDFPanel" runat="server" Visible="False">
<div>
<asp:Literal id="litTitle" runat="server" />
</div>
</asp:Panel>
then in your click method:
litTitle.Text = txtTitle.Text;
PDFPanel.Visible = true;
Set the Panel's visibility to false by default
<asp:Panel ID="PDFPanel" runat="server" Visible="false">
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
</asp:Panel>
then on the Button's click event set the visibility to true
public void btnSubmit(Object sender, EventArgs e)
{
PDFPanel.Visible = true;
// do something else...
}

How to call a clientside script function first and then call a server side button click event?

Here i am trying to do a email validation for a textbox using jquery and am calling that function on onclientclick and i have a button click event too.But the button click event is firing before the javascript function.I need to validate the textbox before firing the button click event.Here is my code
$(document).ready(function () {
$("#MainContent_txtEmail").blur(function () {
ValidateEmail();
});
function ValidateEmail()
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddress = $("#MainContent_txtEmail").val();
if (!emailReg.test(emailaddress)) {
$("#emailspan").html('<font color="red" size=2px;>Please enter valid Email address</font>');
return false;
}
else {
$("#emailspan").html('<font color="red"></font>');
return true;
}
}
});
and
<asp:TextBox ID="txtEmail" name="txtEmail" runat="server" CausesValidation="false" TextMode="Email">
</asp:TextBox><span id="emailspan" value="0"></span>
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmail();" OnClick="btnsubmit_Click"/>
and my event
protected void btnsubmit_Click(object sender, EventArgs e)
{
SendSmtpEmail(txtEmail.Text, "noreply#a.net", "test", "test-template");
}
Any suggestion??
hey In your code ::
`$("#MainContent_txtEmail").blur(function ()
why you are calling the function you may have to change that in to
$("#txtEmail").blur(function ()`
this will work I guess !!
You'll want to remove the OnClick for btnsubmit
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmailThenSubmit();" />
Then click the btnsubmit manually in code after the validation.
function ValidateEmailThenSubmit()
{
ValidateEmail();
$("#" + <%= btnsubmit.ClientID %>).click();
}
Why use javascript? Just use the asp.net RegularExpressionValidator like so:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
More info here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx
The ValidateEmail() method is not visible being declared inside the anonymous method passed as argument to the $.ready() method.
Get the ValidateEmail method outside $(document).ready and it should work.

modal pop-up ok button not working as expected for a dropdown menu

CODE BEHIND:
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlLanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload the page for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
//Server.Transfer(Request.Path);
}
protected void OKButton_Click(object sender, EventArgs e)
{
Server.Transfer(Request.Path);
}
ASPX PAGE:
<asp:DropDownList ID="ddlLanguage" class="langpnl" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="en-US">Eng</asp:ListItem>
<asp:ListItem Value="es-ES">Esp</asp:ListItem>
</asp:DropDownList>
<ajaxToolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="testhidden"
PopupControlID="pnlPopup" OkControlID="OKButton" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" Style="display: none">
All content may not be in Spanish.
<asp:Button ID="OKButton" runat="server" Text="OK" OnClick="OKButton_Click" />
</asp:Panel>
<asp:HiddenField ID="testhidden" runat="server" />
I am trying to set the language as per the selection in the Dropdown box. But if the user selects spanish I want to display a popup modal with a msg & once the button OK is pressed I want to postback the whole page.
Currently I am able to display the popup but the page never refreshed so the language still doesn't change. In the code behind if I remove the server.transfer from the OK button and put it in the SelectIndexChange then the page postback is working but there is no popup masg .I think the page gets postback after the popup executes so it never gets displayed...please need some help I am breaking my head since last 3 days.
Define another button in that panel... and do whatever you want in his onclick event. So you will have a postback.
The OKButton click event... OKButton_Click will not fire as long as you assigned him in you modalpopup...
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
else
{
Server.Transfer(Request.Path);
}
& removed the OK button from Modalpopup..finally got to see what I was Expecting..

Categories