I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
here is the script
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.
so, i tried to make it server side by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
code behind is :
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me
any suggestion on both scenarios will be appreciated. thanks.
client side validation is working, check your code
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="dddate" runat="server">
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true" runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />
<script type="text/javascript">
function abc(sender, args) {
var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
if ((gradeYear - birthYear) > 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
</script>
Related
Entering the user number in the text box with the webmethod GetSearchUser returns the name of user.
I have this regular expression to test if an input starts with the letter "a" or "A" and is followed by 6 numbers. On the online validator seems to work.
The problem is that when the user number is replaced with the the name of user this string is not validated. And it is correct.
But how do I then check that user number is entered correctly and validate the string when the user number is replaced with the the name of user?
My code below.
<asp:AutoCompleteExtender
ServiceMethod="GetSearchUser"
ServicePath="prefix.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</asp:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator29" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required" Text=""
Display="None" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator8" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required : AXXXXXX" Text=""
Display="None" ValidationExpression="/^(a|A)([0-9]{6})$/" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RegularExpressionValidator>
[ScriptMethod()]
[WebMethod]
public static List<string> GetSearchUser(string prefixText)
{
DataTable Result = new DataTable();
string str = #String.Format("SELECT Name FROM `users` ");
str += String.Format(" WHERE user_number LIKE '" + prefixText + "%' ");
str += String.Format(" ORDER BY Name ASC;");
using (OdbcConnection con =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
da = new OdbcDataAdapter(str, con);
dt = new DataTable();
da.Fill(dt);
List<string> Output = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
Output.Add(dt.Rows[i][0].ToString());
return Output;
}
}
EDIT
According to your description, I'm afraid that the <asp:RegularExpressionValidator> is unable to complete two validations at the same time.
What you need might be a custom validator which could do both validation for the text box.
Solution: using <asp:CustomValidator>
You could do validation from both server side and client side (I did it from client side).
It can be used as a combination of RequiredValidator, RegularExpressionValidator and extra custom style validation.
More details, you could refer to below code:
.aspx :
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<ajaxToolkit:AutoCompleteExtender
OnClientItemSelected="itemSelected"
ServiceMethod="GetSearchUser"
ServicePath="AutoCompleteExtenderValidation.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:HiddenField ID="hf_txuser" runat="server" />
<asp:CustomValidator ID="CustomValidatorFortxuser" runat="server"
ClientValidationFunction="custom_validation" ControlToValidate="txuser"
Display="Dynamic" ErrorMessage="Required AXXXX or Valid UserName"
ValidationGroup="ValidationSummaryUser" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<asp:Button ID="SubmitBtn" runat="server" ValidationGroup="ValidationSummaryUser" Text="Submit" OnClick="Submit_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
Javascript code:
<script type="text/javascript">
function itemSelected(sender, ev) {
//When selected value from the return list, it will be kept in the hidden field for the following validation
var selectedValue = ev._value;
$('#<%= hf_txuser.ClientID%>').val(selectedValue);
}
function custom_validation(source, arguments) {
if (arguments.Value == "") {
arguments.IsValid = false;
} else {
//Valid if one of checks pass: fulfill the regex or equals to hidden field value. No worries about the empty content
arguments.IsValid = (regexValidate(arguments) || arguments.Value == $('#<%= hf_txuser.ClientID%>').val());
}
if (!arguments.IsValid) {
$('#<%= Label1.ClientID%>').text("");
}
}
function regexValidate(input) {
var patt = /^(a|A)([0-9]{6})$/;
return patt.test(input);
}
</script>
.cs code:
protected void Submit_Click(object sender, EventArgs e)
{
Label1.Text = txuser.Text + " Submit successfully!";
}
You should include Jquery in the <head> since I have used Jquery in the code for assigning value to the hidden field.
<head runat="server">
<title></title>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
The version could be any one as long as it works for value assignment.
Hope this can help you.
I have created custom validation in aspx file for checkboxlist like
<asp:UpdatePanel ID="pnlUpdateAgency" runat="server">
....
....
<script type="text/javascript">
function validateCheckbox(sender, e) {
try {
e.IsValid = false;
var checkboxlist = document.getElementById('chklLineOfAuthority');
var inputlist = checkboxlist.getElementsByTagName('input');
for (var i = 0; i < inputlist.length; i++) {
if (inputlist[i].type == 'checkbox')
if (inputlist[i].checked) {
e.IsValid = true;
break;
}
}
}
catch (ex) {
alert(ex.Message);
}
}
</script>
...
...
<asp:CheckBoxList ID="chklLineOfAuthority" RepeatColumns="3" RepeatLayout="Table"
RepeatDirection="Horizontal" AutoPostBack="false" CausesValidation="false"
runat="server">
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please select at least one option"
ClientValidationFunction="validateCheckbox"
ForeColor="Red" />
...
...
</asp:UpdatePanel>
Now the issue is custom validation not working in update panel.
So I have a few ASP.NET file upload controls in my aspx file -
<asp:FileUpload ID="fulNature" class="form-control summer" runat="server" /><asp:Labe ID="lblNature" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fulNature" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
<asp:FileUpload ID="fulIndustrial" class="form-control summer" runat="server" /><asp:Label ID="lblIndustrial" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="fulIndustrial" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
I'm trying to limit file size with one C# validator -
protected void ValidateFileSize(object source, ServerValidateEventArgs args)
{
var validator = (source as CustomValidator);
string controlToValidate = validator.ControlToValidate;
FileUpload SubmittedUpload = validator.NamingContainer.FindControl(controlToValidate) as FileUpload;
if (SubmittedUpload.FileBytes.Length > 1048576) // A little padding added.
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
The issue is that the validator never fires regardless of file size. I have to be missing something simple here, but I'm just not seeing it.
you can directly get the size of uploaded file:
long size=fulNature.FileContent.Length;
Try:
long filesize = SubmittedUpload.FileContent.Length;
Following is the test scenario for my code.
1) Once the user selects one of the radio buttons on Webpage.aspx, a modal popup extender shows up.
2) A user control (SSL_Ticket.ascx) is defined inside the modal popup window.
3) A RequiredFieldValidator is defined for a drop down list contained inside the user control.
4) If the user selects the "0" value from drop down list, no validation error message is displayed.
Code
Webpage.aspx
<asp:RadioButtonList ID="RadioButtonListForTicket" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="radioButtonListForTicket_OnSelectedIndexChanged">
<asp:ListItem Selected="True">No</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:RadioButtonList>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderForTicket" runat="server" BackgroundCssClass="popUpStyle"
DropShadow="true" PopupControlID="divTicketPreview" PopupDragHandleControlID="panelDragHandle"
TargetControlID="btnForPopupAppear" CancelControlID="btnForPopupDisappear"/>
....
...
Webpage.aspx.cs
protected void radioButtonListForTicket_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
if (RadioButtonListForTicket.SelectedItem.Text.ToString().Equals("Yes"))
{
// Check if the sites are selected
updateSelectionCount();
updateListOfSites();
if (selectionCount == 0)
{
lblSSLTicketSelection.Text = "Please select a site.";
RadioButtonListForTicket.SelectedValue = "No";
return;
}
else
{
lblSSLTicketSelection.Text = "";
}
....
ModalPopupExtenderForTicket.Show();
}
}
...
SSL_Ticket.ascx
<asp:DropDownList ID="cmbRootCause" runat="server" Width="255px" OnSelectedIndexChanged="cmbRootCause_SelectedIndexChanged" AutoPostBack="true"
CausesValidation="true">
<asp:ListItem Value="0">Select</asp:ListItem>
<asp:ListItem Value="1">Item1</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" Visible="false" Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
...
SSL_Ticket.ascx.cs
protected void cmbRootCause_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRootCause.SelectedItem.ToString().Equals("Other"))
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = true;
}
else if (cmbRootCause.SelectedItem.ToString().Equals("Select"))
{
lblcmbRootCause.Visible = true;
lblcmbRootCause.Text = "Please select root cause";
}
else
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = false;
}
}
I did browse through couple of solutions (ValidateProperty, Client-side validation, RangeValidation, etc), but it did not fire validation text.
This did not help - Handling RequiredFieldValidator inside of a User Control
I'd appreciate your help very much.
Thanks!!!
Remove visible = false attribute from required field validator, by default they won't show up in the beginning.
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" **Visible="false"** Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
Well in your 'RequiredFieldValidator' for your DropDownList you need to remove this:
InitialValue="Select"
I have an ASP.NET form for currency exchange requests. There are two text fields there: amount-source and amount-target.
One of them must be filled and only one.
How to implement this using Validators, if applicable?
You can use Custom Validators for this:
<asp:Textbox id="textbox1" runat="server" />
<asp:CustomValidator id="valCustom" runat="server"
ControlToValidate="textbox1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidate"
ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>
<asp:Textbox id="textbox2" runat="server" />
<asp:CustomValidator id="valCustom2" runat="server"
ControlToValidate="textbox2"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidate"
ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>
<script language="Javascript">
function ClientValidate(source, arguments)
{
var tb1 = document.getElementById("<%=textbox1.ClientID %>").value;
var tb2 = document.getElementById("<%=textbox2.ClientID %>").value;
if (tb1 && tb2 || (!tb1 && !tb2)){
arguments.IsValid = false;
} else {
arguments.IsValid = true;
}
}
</script>
Server-side:
protected void ServerValidate(object sender, ServerValidateEventArgs args)
{
if(string.isNullOrEmpty(textbox1.Text) && string.isNullOrEmpty(textbox2.Text))
args.IsValid = false;
else if(!string.isNullOrEmpty(textbox1.Text) && !string.isNullOrEmpty(textbox2.Text))
args.IsValid = false;
else
args.IsValid = true;
}
If you're using jQuery please comment...this can all be much cleaner.
I would implement a custom Validator and decorate both TextBoxes with it. If both are filled, then both are in a error state.