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
Related
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;
Java script code:
<script language="javascript" type="text/javascript">
function validateLoginForm() {
if (document.getElementById("<%=txtTitle.ClientID%>").value == "") {
alert("Please Enter Title");
txtTitle.focus();
return false;
}
}
Button Code
<asp:Button ID="btnPost" UseSubmitBehavior="false" Text="Post" OnClientClick="javascript:validateLoginForm();" runat="server" OnClick="btnPost_Click" />
This code is not working on internet explorer but works fine in firefox
even though the javascript returns false in onClientClick event
the onClick event is still getting called
Please Help...!!!
It can be solved using
<asp:Button ID="btnPost" UseSubmitBehavior="false" Text="Post" OnClientClick="return validateLoginForm();" runat="server" OnClick="btnPost_Click" />
Replace your Java script function with this
function validateLoginForm() {
if (document.getElementById("<%=txtTitle.ClientID%>").value == "") {
alert("Please Enter Title");
txtTitle.focus();
return false;
}
else
return true;
}
And you OnClientClick attribute with this
OnClientClick="javascript:return validateLoginForm();"
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 .
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.
I have validation as below but only like to triggered if the checkbox is ticked.
<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator1"
Text="*"
ErrorMessage="Name is required"
ControlToValidate="TextBox1" />
Can I get it done using asp:RequiredFieldValidator?
I only like to validate if a certain condition matched.
Currently it is validating every time the 'Save' button is clicked.
Use a custom validator instead:
<asp:CustomValidator ID="cv1" runat="server"
ErrorMessage="Name is required"
Text="*"
ControlToValidate="TextBox1"
ValidateEmptyText="True"
ClientValidationFunction="validate" />
and the script (just checking a checkbox and the textbox value as example; you can use custom logic):
<script type="text/javascript">
function validate(s,args){
if(document.getElementById("<%= checkboxId.ClientID %>").checked){
args.IsValid = args.Value != '';
}
else{
args.IsValid = true;
}
}
</script>
This will do the client-side validation. If you need server validation also, add the OnServerValidate attribute, and a handler on code behind. See here for details.
I solved this easily by adding the following javascript on Client side.
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);
You can also try this one
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox.Checked)
{
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ValidationGroup = "anything";
Button1.ValidationGroup = "anything";// your save button
}
else
{
RequiredFieldValidator1.Enabled = false;
RequiredFieldValidator1.ValidationGroup = string.Empty;
Button1.ValidationGroup = string.Empty; // save button
}
}
Try this...
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
RequiredFieldValidator1.Enabled = true;
}
else if (CheckBox1.Checked == false)
{
RequiredFieldValidator1.Enabled = false;
}
}
You can enabled/Disabled the RequiredFieldValidator from the Javascript/jQuery.
For your condition, When Checkbox is checked :- Just call the javascript function to enabled the RequiredFieldValidator and when its Uncheck just disabled the RequiredFieldValidator.
For other Conditions like Dropdown index change, textbox value change and radio button selection change you can call its onchange, onblur, onclick respectively and
After executing the required condition you can Enabled/Disabled the RequiredFieldValidator.
Hope this help you.