Regular expression for maximum digits excluding comma - asp.net

I have the below regular expression:
ValidationExpression="[0-9]+(,[0-9]+)*"
It allows numbers in the format: 12,2345 or 231,23454
Now I want to include a condition that will on the whole allow only 7 digits max excluding
comma.
The below is the modified code
The below is in the item template
I also have a radio button in item template
<asp:TextBox runat="server" ID="tbText" CssClass="someclass" MaxLength="11"
%>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationExpression="[0-9]+(,[0-9]+)*" ID="ValComp" runat="server" CssClass="asdf"
ControlToValidate="tbMileage" Text="*" Enabled="false" Display="Dynamic"/>
<asp:CustomValidator ID="cvalMileage" runat="server" CssClass="adsf" Text="*" Display="Dynamic">
</asp:CustomValidator>
<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="functionName"
runat="server" CssClass="asd" Text="*" Display="Dynamic">
</asp:CustomValidator>
Since I want to validate the radio button checked corresponding textbox in repeater the below is the code I have written
var selText = $(".Class1 input[type=radio]:checked").closest(".Class1").find(".subClassText input[type=text]").val();
alert('Hi');
if (selText.replace(",", "").length <= 7) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
The alert fires twice and based on args is False i have a popup that is firing twice
Thanks.

Regular expressions are not good at this problem, but if you limit your input to a maximum of one comma this expression will fit:
([0-9]{0,0}[,]?[0-9]{0,7})|([0-9]{0,1}[,]?[0-9]{0,6})|([0-9]{0,2}[,]?[0-9]{0,5})|([0-9]{0,3}[,]?[0-9]{0,4})|([0-9]{0,4}[,]?[0-9]{0,3})|([0-9]{0,5}[,]?[0-9]{0,2})|([0-9]{0,6}[,]?[0-9]{0,1})|([0-9]{0,7}[,]?[0-9]{0,0})
You will recognize that this problem is not well suited for regular expression as this expression is fixed to your maximum of 7.

You could use a CustomValidator control with client-side validation like this:
ASPX code:
<asp:CustomValidator id="CustomValidator1" runat="server"
ControlToValidate="YourControlNameHere"
ClientValidationFunction="ClientValidation"
OnServerValidate="ServerValidation"
ErrorMessage="Invalid number." />
JavaScript (uses jQuery):
function ClientValidation(source, arguments)
{
var inputText = arguments.Value;
var expression = /^[0-9]+(,[0-9]+)*$/;
if (expression.test(inputText) && inputText.replace(",", "").length <= 7) {
arguments.IsValid = true;
}
else {
arguments.IsValid = false;
}
}
C# code behind:
public void ServerValidation(object source, ServerValidateEventArgs args)
{
string inputText = args.Value;
Regex regex = new Regex(#"^\d+(,\d+)*$");
if (regex.IsMatch(inputText) && inputText.Replace(",", "").Length <= 7)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

Related

ASP.Net Custom Validator failed ,form gets submitted

I have made a form in which there are two RAD DateTimePicker Controls . One is for Start-DateTime and other is for End Date Time. Inside Custom Validator, I have Compared the Date Time Picked So far and hence made it valid or invalid accordingly its Server Validate event code goes like this.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Its Design Code goes like this.
<telerik:RadDateTimePicker ID="rdpStartDate" runat="server" AutoPostBackControl="Both" onselecteddatechanged="rdpStartDate_SelectedDateChanged">
<TimeView CellSpacing="-1" Culture="en-IN">
</TimeView>
<TimePopupButton HoverImageUrl="" ImageUrl="" />
<Calendar UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x">
</Calendar>
<DateInput AutoPostBack="True" DateFormat="dd-MM-yyyy" DisplayDateFormat="dd-MM-yyyy">
</DateInput>
<DatePopupButton HoverImageUrl="" ImageUrl="" />
</telerik:RadDateTimePicker>
<asp:Label ID="Label2" runat="server" Text=" To" CssClass="h_text"></asp:Label>
<telerik:RadDateTimePicker ID="rdpEndDate" runat="server" onselecteddatechanged="rdpEndDate_SelectedDateChanged" AutoPostBackControl="Both">
<TimeView CellSpacing="-1" Culture="en-IN"></TimeView>
<TimePopupButton ImageUrl="" HoverImageUrl=""></TimePopupButton>
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x"></Calendar>
<DateInput DisplayDateFormat="dd-MM-yyyy" DateFormat="dd-MM-yyyy" AutoPostBack="True"></DateInput>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
</telerik:RadDateTimePicker>
Validator Source Code in designer is like this.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
I want to ask that even when custom validator fails, My form gets submitted with faulty values. What can be the reason? How can I avoid that?
With Server validator Event like:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You have to check on your server event as well like:(For example if you are using your validator with button click then)
protected void btn_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Write("Page is valid.");
}
else
{
Response.Write("Page is not valid!");
}
}
My suggestion: Telerik has a good client side support as well so I suggest you to use client side validation of custom validator.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
ClientValidationFunction="CheckDates"
SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
then in Javascript:
function CheckDates(sender, args)
{
var cltRdpEndDate= $find("<%=rdpEndDate.ClientID %>");
var cltRdpStartDate= $find("<%=rdpStartDate.ClientID %>");
if(cltRdpEndDate.get_dateInput().get_selectedDate()< cltRdpStartDate.get_dateInput().get_selectedDate())//if your condtion fails here
{
args.IsValid = false;
return;
}
args.IsValid = true;
}

Validate TextBox based on DropDownList selection

I need to validate TextBox based on Value selected in DropDownList controls. I have asp:TextBox and asp:DropDownList controls.
If user selects Yes option from the first dropdown he must type value in text box. How can I validate second box? Thanks for help.
The simplest approach is to set the DropDownList's AutoPostBack property to true and handle it's SelectedIndexChanged event. Then you can Enable/Disable the validator there.
Another approach is to use a CustomValidator. This validator is not dependent on a single control. You must write the validation rules on your own. For example the ClientValidationFunction:
<script type="text/javascript" >
function ClientValidate(source, arguments) {
var txt = document.getElementById('TextBox1');
var ddl = document.getElementById('DropDownList1');
var decision = ddl.options[ddl.selectedIndex].text;
if(decision=='Yes'){
arguments.IsValid = txt.value.length > 0;
}else{
arguments.IsValid = true;
}
}
</script>
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem Selected="False">No</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="TextBox1" runat="server" />
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />
<asp:CustomValidator id="CustomValidator1"
ValidateEmptyText="true"
ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Please enter text!"
runat="server"/>
Remember to always implement a OnServerValidate because you should not rely on javascript only(can be disabled). This is easy:
void ServerValidation(object source, ServerValidateEventArgs args){
args.IsValid = DropDownList1.SelectedIndex == 1 || TextBox1.Text.Length > 0;
}
VB.NET
Protected Sub ServerValidation(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
args.IsValid = DropDownList1.SelectedIndex = 1 OrElse TextBox1.Text.Length > 0
End Sub
Add this code to your submit button.
if(DropDownList1.SelectedItem.Text.Equals("Yes") && TextBox1.Text.Length==0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Enter data in the textbox !');", true);
}
Add a CustomValidator control, that validates the TextBox, from there you'll have to do something like this (assuming C#) in the CustomValidator_ServerValidate event handler:
bool valid = false;
if (dropDownList.SelectedValue.Equals("yes")) {
valid = !String.IsNullOrEmpty(textBox.Text);
}
return valid;

Range Validator - alphabet entered when integer range checked

I have a Range Validator as follows. It is for restricting values between 1900 and 2070. However, it fires error when I enter a alphabet also. I want this to be fired only if the user enters integer values. How do I overcome it? Please help..
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtYear"
ValidationGroup="report" ErrorMessage="EM1|Year" MaximumValue="2079" MinimumValue="1900"
SetFocusOnError="True" Display="Dynamic" Type="Integer">
<img src="../../Images/error.gif" alt="Format" />
</asp:RangeValidator>
You can use custom validator in this case.
It may look like this
Use this as your validator code -
<asp:customvalidator ID="Customvalidator1" ControlToValidate="txtYear" runat="server"
EnableClientScript="true"
errormessage="CustomValidator"
onservervalidate="Customvalidator1_ServerValidate"></asp:customvalidator>
Use this in your code behind -
protected void Customvalidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int result;
if (int.TryParse(txtYear.Text,out result))
{
if (1900 <= result && result <= 2079)
args.IsValid = true;
else
args.IsValid = false;
}
args.IsValid = true;
}

asp.net validate textbox - at least one text box must have data in

I have three textboxes and I want to validate them. At least one textbox must contain data.
How can I do this?
(The textboxes are Home Phone No., Work Phone No., Mobile No. and I need to check at least one method of contact is specified)
<script language="javascript">
function Validate(sender, args){
args.IsValid = false;
if(args.Value != "")
{
args.IsValid = true;
}}</script>
the above function dont validate that at least one textbox contains data it validate that the control attached to the validator have data. Just use one custom validator like this
<asp:TextBox ID="txtHomePhone" runat="server"></asp:TextBox>
<asp:TextBox ID="txtWorkPhone" runat="server"></asp:TextBox>
<asp:TextBox ID="txtMobilePhone" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvMobilePhone" runat="server" ErrorMessage="ADASDASDA" ClientValidationFunction="Validate"
ValidateEmptyText="true"></asp:CustomValidator>
<script language="JavaScript">
function Validate(sender, args) {
var txt1 = document.getElementById("<%= txtHomePhone.ClientID %>");
var txt2 = document.getElementById("<%= txtWorkPhone.ClientID%>");
var txt3 = document.getElementById("<%= txtMobilePhone.ClientID%>");
args.IsValid = (txt1.value != "") || (txt2.value != "") || (txt3.value != "");
}
</script>
In case you want to reuse the function you can add attributes to your validation object.
Check it out: http://alejandrobog.wordpress.com/2009/09/27/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/
Use a Custom validator, with ClientValidationFunction property to this function.
function validate(source, arguments) {
var textboxes = document.getElementsByTagName("INPUT");
for (var i = 0; i < textboxes.length; i++) {
if (textboxes[i].type == "text" && textboxes[i].value != "") {
arguments.IsValid = true;
return;
}
}
arguments.IsValid = false;
}
Use a Custom Validator, there is no need to cycle through the text boxes on the page as this approach gets ALL of the text boxes on the page. The JavaScript function specified in the ClientValidationFunction will be called for each text box with a validator associated with it.
<asp:TextBox ID="txtHomePhone" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvHomePhone" runat="server" ErrorMessage="*" ClientValidationFunction="Validate" ControlToValidate="txtHomePhone" ValidateEmptyText="true"></asp:CustomValidator>
<asp:TextBox ID="txtWorkPhone" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvWorkPhone" runat="server" ErrorMessage="*" ClientValidationFunction="Validate" ControlToValidate="txtWorkPhone" ValidateEmptyText="true"></asp:CustomValidator>
<asp:TextBox ID="txtMobilePhone" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvMobilePhone" runat="server" ErrorMessage="*" ClientValidationFunction="Validate" ControlToValidate="txtMobilePhone" ValidateEmptyText="true"></asp:CustomValidator>
<script language="javascript">
function Validate(sender, args)
{
args.IsValid = false;
if(args.Value != "")
{
args.IsValid = true;
}
}
</script>

How do I make a checkbox required on an ASP.NET form?

I've done some searching on this, and I've found several partial answers, however nothing that gives me that warm fuzzy "this is the right way to do this". To answer the most frequently occurring complaint against this question: "checkboxes can have two legitimate states - checked and unchecked", this is an "I accept the terms and conditions..." checkbox which must be checked in order to complete a registration, hence checking the box is required from a business logic standpoint.
Please provide complete cut-n-paste ready code fragments with your response! I know there are several pieces to this -- the CustomValidator (presumably), the code-behind, some javascript and possibly a check for IsValid, and the frustrating part for me is that in each example I've seen, one of these critical pieces is missing!
javascript function for client side validation (using jQuery)...
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}
code-behind for server side validation...
protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = MyCheckBox.Checked;
}
ASP.Net code for the checkbox & validator...
<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
OnServerValidate="CheckBoxRequired_ServerValidate"
ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
and finally, in your postback - whether from a button or whatever...
if (Page.IsValid)
{
// your code here...
}
C# version of andrew's answer:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please accept the terms..."
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:CheckBox ID="CheckBox1" runat="server" />
Code-behind:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = CheckBox1.Checked;
}
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return #"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.
The .ascx:
<script type="text/javascript">
function checkAgreement(source, args)
{
var elem = document.getElementById('<%= chkAgree.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
function checkAge(source, args)
{
var elem = document.getElementById('<%= chkAge.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />
<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAgreement">
You must agree to the terms and conditions.
</asp:CustomValidator>
<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAge">
You must be 18 years or older to continue.
</asp:CustomValidator>
And the codebehind:
Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
e.IsValid = chkAgree.Checked
End Sub
Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
e.IsValid = chkAge.Checked
End Sub
I typically perform the validation on the client side:
<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server" />
<asp:CustomValidator id="vTerms"
ClientValidationFunction="validateTerms"
ErrorMessage="<br/>Terms and Conditions are required."
ForeColor="Red"
Display="Static"
EnableClientScript="true"
ValidationGroup="vg"
runat="server"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
<script>
function validateTerms(source, arguments) {
var $c = $('#<%= chkTerms.ClientID %>');
if($c.prop("checked")){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
Non-javascript way . .
aspx page:
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>
Code Behind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If Not CheckBox1.Checked Then
args.IsValid = False
End If
End Sub
For any actions you might need (business Rules):
If Page.IsValid Then
'do logic
End If
Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(

Resources