custom validator is not working in asp.net - asp.net

<asp:TextBox ID="TextBox3" runat="server" Width="127px"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Must Be 8 characters"
onservervalidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="g1">*</asp:CustomValidator>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="LogIn"
ValidationGroup="g1" Width="83px" />
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value.Length == 8)
{
args.IsValid = true;
}
else
args.IsValid = false;
}
I want textbox to take 8 characters.But the event is not getting fired up.I haved tried by taking Required Field Validator as well as ValidateEmptyText to true but either of them is not working
Please Help.

Try adding a RequiredFieldValidator for the TextBox too, and it should trigger the custom validator server validate event.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Required">
</asp:RequiredFieldValidator>

Related

How to Use Required Field validator on a check box CHECKED true or false

I have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check
<asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />
<div class="col-xs-9 form-inline" id="PChange" style="display: none;">
<asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password" ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>
</div>
gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.
<asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />
If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?
Java script function to show/hide div.
<script type="text/javascript">
function showhidepasswordFields() {
if (document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'block';
}
else if (!document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'none';
}
}
</script>
You can use a CustomValidator for that. The first function just test wether the CheckBox is checked or not. The other one adds more logic like checking if a TextBox also has a value. Just change the ClientValidationFunction for testing.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="testCheckBoxAndTextBox"></asp:CustomValidator>
<script type="text/javascript">
function testCheckBox(sender, element) {
element.IsValid = $("#<%= CheckBox1.ClientID %>").prop('checked');
}
function testCheckBoxAndTextBox(sender, element) {
var isValid = false;
if ($("#<%= CheckBox1.ClientID %>").prop('checked') == true && $("#<%= TextBox1.ClientID %>").val() != "") {
isValid = true;
}
element.IsValid = isValid;
}
</script>
.aspx:
<asp:CheckBox ID="cbTest" runat="server" OnCheckedChanged="cbTest_CheckedChanged"></asp:CheckBox>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFV" Enabled="false" runat="server" ErrorMessage="*****" ControlToValidate="txtTest" ></asp:RequiredFieldValidator>
.aspx.cs:
protected void cbTest_CheckedChanged(object sender, EventArgs e)
{
reqFV.Enabled = cbTest.Checked;
}

Custom Validator validation not firing for textbox in asp.net

<asp:TextBox ID="txtDOB" runat="server" CssClass="textbox_width_height"
placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic"
Enabled="true" ValidateEmptyText="true" SetFocusOnError="true"
OnServerValidate="CustomValidator1_OnServerValidate"
ControlToValidate="txtDOB"
ErrorMessage="Age must be grater than 16 years" >
</asp:CustomValidator>
and here is the event
protected void CustomValidator1_OnServerValidate(object source, ServerValidateEventArgs args)
{
DateTime todayDate = System.DateTime.Now;
DateTime textDOB = Convert.ToDateTime(txtDOB.Text);
DateTime total = todayDate.AddYears(-16);
if (textDOB <= total)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
Place AutopostBack="True" it will become something like this
<asp:TextBox ID="txtDOB" AutoPostBack="true" runat="server" CssClass="textbox_width_height" placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>
Hope it helps

CompareValidator asp.net Type:String

I am trying to use CompareValidator witch compare the field for string.and the
server code to write in the Label1 the result.I tried with integer and date data types and it
work fine but when i put string its not working.When i put integer in the field it consider that is true.How to make it work.
<asp:TextBox ID="name" runat="server" CausesValidation="True" MaxLength="40"> </asp:TextBox>
<asp:CompareValidator
ID="CompareValidator1"
runat="server"
ControlToValidate="name"
Operator="DataTypeCheck"
Type="String">
</asp:CompareValidator>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="True"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Изпрати" BackColor="Black" BorderColor="Black" BorderStyle="None" ForeColor="White" OnClick="PageValidate_SendMail" />
protected void PageValidate_SendMail(object sender, EventArgs e)
{
if (Page.IsValid) {
Label1.Text = "String";
}
else {
Label1.Text = "Integer";
}
}
What you will need is RegularExpressionValidator something like below. The ValidationExpression="^[a-zA-Z]*$ restricts input to alphabets only.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="name" ValidationExpression="^[a-zA-Z]*$" ErrorMessage="RegularExpressionValidator" Display="Dynamic"></asp:RegularExpressionValidator>
You might want to use RequiredFieldValidator as well for checking empty input.
And if none of those meet your requirements then you will need to use CustomValidator.

asp validation summary does not display even though validation fires up for requiredfieldvalidator

The Validation Summary which is to be displayed:
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"
EnableClientScript="true" runat="server" ValidationGroup="downloadGrp" />
The required field validator:
<asp:UpdatePanel ID="UpdatePanel4" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="txtReasonForDownload"
ValidationExpression="^[\s\S]{0,500}$"
ValidationGroup="downloadGrp"
ErrorMessage="Max. 500 characters allowed!" runat="server">
</asp:RegularExpressionValidator><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtReasonForDownload" EnableClientScript="false"
ErrorMessage="Reason is required!" ValidationGroup="downloadGrp"
SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
<asp:Label ID="Label2" runat="server" CssClass="error"
Text="Reason for Download:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"
ValidationGroup="downloadGrp"
Width="200px" MaxLength="500" Enabled="False"></asp:TextBox><br />
</ContentTemplate>
The code behind:
protected void btnSubmitDownload_Click(object sender, EventArgs e)
{
string str1 = txtReasonForDownload.Text;
if (str1.Equals(string.Empty))
{
reqTxtReason.IsValid = false;
//Response.Write("<script> alert('Reason for Download is required!'); </script>");
} else { }
}
Although the requiredfieldvalidator is fired up, the validation summary does not display the validation.
Fixed it by enclosing validation summary in another update panel and by using the same trigger as the other update panel

asp.net regex validator conundrum

input '12', click button, a is false, b is true... note that EnableClientScript is set to false.
<asp:TextBox ID="TextBox1" runat="server"
Width="20px" MaxLength="3"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" EnableClientScript="false" ControlToValidate="TextBox1"
ErrorMessage="RegularExpressionValidator"
ValidationExpression="([1-9]|[1-9][0-9]|[1-9][0-9][0-9])"
ForeColor="Red"><sup>invalid</sup></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate();
bool a = RegularExpressionValidator1.IsValid;
bool b = System.Text.RegularExpressions.Regex.IsMatch(TextBox1.Text,
RegularExpressionValidator1.ValidationExpression);
}
Replace ValidationExpression with:
ValidationExpression="^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$"

Resources