Button Click fires before custom validation occurs - c#

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;

Related

Custom Validation doesn't fire

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.

TextBox Custom Web Control and JavaScript Client Validation

I have created custom web control textbox which is working fine and its code is as below:
public class ReqTextBox : TextBox
{
private RequiredFieldValidator req;
public string ErrMsg { get; set; }
protected override void OnInit(EventArgs e)
{
this.CssClass = "inp-form";
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = string.IsNullOrEmpty(this.ErrMsg) ? "*" : this.ErrMsg;
req.Display = ValidatorDisplay.Dynamic;
//req.EnableClientScript = true;
if (!string.IsNullOrEmpty(this.ValidationGroup))
req.ValidationGroup = this.ValidationGroup;
Controls.Add(req);
//base.OnInit(e);
}
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
req.RenderControl(w);
}
}
This is working fine with following code:
<Mas:ReqTextBox runat="server" ID="txtCustBankCode" Width="236px" ValidationGroup="vmas" ErrMsg="Enter BankName"></Mas:ReqTextBox>
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
Here it works fine. Now if i add onclientclick event on button then it will not check if textbox is empty or not. In both return true and false in Valid() function it's not working.
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" onClientClick="return Valid();" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
What am i missing...?
req.EnableclientScript = true/false;
did not help me.
Need Help.
Thanks.
EDIT: I need to use this Customcontrol, so that user need to enter some data and for those entered data, i need to validate with javascript function. Sorry for late EDIt.
Use customvalidator with custom clientvalidation function:
<script type="text/javascript">
function ClientValidate(source, arguments) {
if (arguments.Value === "foo") {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid entry" ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
Read more from here .

ValidationSummary in MasterPage hide success label

I've got a ValidationSummary and SuccessLabel in the MasterPage
When the SuccessLabel has detail in it, and then the ValidationSummary then fails validation I want it to hide the SuccessLabel and only show the ValidationSummary.
<div id="ApplicationStatus" class="ValidationSummaryContainer">
<asp:Label ID="StatusLabel" CssClass="SuccessSummary" runat="server"
Visible="false"></asp:Label>
<asp:Label ID="WarningLabel" CssClass="WarningSummary" runat="server"
Visible="false"></asp:Label>
<asp:ValidationSummary ID="ErrorValidationSummary" runat="server"
CssClass="ValidationSummary" DisplayMode="List" />
<asp:CustomValidator ID="ErrorCustomValidator" runat="server"></asp:CustomValidator>
</div>
<div id="ApplicationContent" class="ApplicationContentContainer">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StatusLabel.Text = "Successfully loaded record";
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Textbox ID = "Text1" runat="server"/>
<asp:RequiredFieldValidator id="InputTextBoxRequiredFieldValidator" runat="server"
ControlToValidate="Text1" Visible="false" CssClass="InlineNoWrap" Enabled="true">
</asp:RequiredFieldValidator>
<asp:Button ID = "Button1" runat="server" Text="Submit"/>
</asp:Content>
I'm trying to find a way in JavaScript to catch the validation error and hide the StatusLabel.
I don't want to have to put a javascript function on every button on every page that uses the MasterPage.
Thanks,
Alex
How about something like this:
protected void Submit(object sender, EventArgs e)
{
if (IsValid)
{
StatusLabel.Visible = true;
}
else
{
StatusLabel.Visible = false;
}
}
Your validation code are totally miss lot of fields.
ok now we are going your pint .
Set visible false in your label for page load event
then success time add the label text ,and set visible true
you miss control to validate and validationgroup and display fields
please see this sample

Custom validator getting invoked onclick of all controls on the page

i have written a custom validation function to check if a panel is displayed
i want the function to be invoked onclick of NEXT button.
But instead it gets invoked onclick of every button on the page.
Here is the code:
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
and this is the button code onclick of which it should be invoked.
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
if i set Controltovalidate="btnNext" then it again throws me error.
"btnNext cannot be validated".
You need to hook it to the right element.
document.getElementById("btnNext").onclick = function() {
//Do Your Stuff Here
};
Angela
Hey i did a very simple solution to my problem.
first is the java script code that ws getting invoked onclick of evry button on the page.
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
Then on the Next button:
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
and for the rest of buttons i did set causesvalidation=false property. with this the function wwas getting invoked only on Next button

How can I reload ReCaptcha control after custom validation?

I have ReCaptcha control on my registration form:
<recaptcha:RecaptchaControl ID="ReCaptcha" runat="server" PublicKey="<%$ appSettings:ReCaptchaPublicKey %>" PrivateKey="<%$ appSettings:ReCaptchaPrivateKey %>" Theme="white" />
<asp:CustomValidator ID="ReCaptchaCustomValidator" runat="server" ErrorMessage="ReCaptcha error message." Display="None" ValidationGroup="Step1" EnableClientScript="true" OnServerValidate="ReCaptcha_ServerValidate" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" ValidationGroup="Step1" CssClass="validationSummary" />
CodeBehind
protected void ReCaptcha_ServerValidate(object source, ServerValidateEventArgs e)
{
ReCaptcha.Validate();
if (ReCaptcha.IsValid)
e.IsValid = true;
else
e.IsValid = false;
}
If user enter ReCaptcha value not properly, ReCaptcha control disappear after server-side validation.
How can I reload it after validation?
protected void Page_PreRender(object sender, EventArgs e)
{
CaptchaControl1.Enabled = true;
}

Categories