CompareValidator asp.net Type:String - asp.net

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.

Related

ASP.Net Prevent compare validator and regular expression validator from firing at the same time

I've got two text boxes like this:
<asp:TextBox ID="textBox1" runat="server" />
<asp:RegularExpressionValidator ID="regExTextBox1" runat="server" ControlToValidate="textBox1" ErrorMessage="Not a positive real number." Display="Dynamic" ValidationExpression="(^0*[1-9]+\d*(\.\d+)?$)|(^0*\.0*[1-9]+\d*$)" />
<asp:RequiredFieldValidator ID="reqFldTextBox1" runat="server" ControlToValidate="textBox1" ErrorMessage="Enter a number." Display="Dynamic" />
<asp:TextBox ID="textBox2" runat="server" />
<asp:RegularExpressionValidator ID="regExTextBox2" runat="server" ControlToValidate="textBox2" ErrorMessage="Not a positive real number." Display="Dynamic" ValidationExpression="(^0*[1-9]+\d*(\.\d+)?$)|(^0*\.0*[1-9]+\d*$)" />
<asp:RequiredFieldValidator ID="reqFldTextBox2" runat="server" ControlToValidate="textBox2" ErrorMessage="Enter a number." Display="Dynamic" />
<asp:CompareValidator id="compareValidator" runat="server" ControlToValidate="textBox2" ControlToCompare="textBox1" Type="Double" Display="Dynamic" Operator="LessThan" Text="Error." />
It's two text boxes that have regular expression validators that constrain them to only allow positive real numbers. These work fine.
I also want the input in the second text box to be smaller than the first one. For that I have a compare validator.
When the user has correct numbers the compare validator works fine.
It's when they enter in anything that fails the second regular expression validator, that the compare validator also fires at the same time.
It doesn't matter what's in the first text box, valid input, wrong input, or even nothing. Both of the second validators fail.
Even though the validator is supposed to be comparing doubles.
Is there an easy fix for this?
I realize that this behavior is okay, because a validator is invalid when it should be, but the user would be seeing the incorrect error messages.
I've already done a solution involving custom validators and Javascript, and if it comes down to it then I'll have to do that again. But if that's the case then there's not much point to using a compare validator, since it'll never work with a regular expression validator.
Assign different validation groups to regular expression validator and compare validator and use ASP.NET inbuilt javascript function Page_ClientValidate() to check validation one by one.
<asp:TextBox ID="textBox1" runat="server" />
<asp:RegularExpressionValidator ID="regExTextBox1" runat="server" ControlToValidate="textBox1" ErrorMessage="Not a positive real number." Display="Dynamic" ValidationExpression="(^0*[1-9]+\d*(\.\d+)?$)|(^0*\.0*[1-9]+\d*$)" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="reqFldTextBox1" runat="server" ControlToValidate="textBox1" ErrorMessage="Enter a number." Display="Dynamic" ValidationGroup="Group2"/>
<asp:TextBox ID="textBox2" runat="server" />
<asp:RegularExpressionValidator ID="regExTextBox2" runat="server" ControlToValidate="textBox2" ErrorMessage="Not a positive real number." Display="Dynamic" ValidationExpression="(^0*[1-9]+\d*(\.\d+)?$)|(^0*\.0*[1-9]+\d*$)" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="reqFldTextBox2" runat="server" ControlToValidate="textBox2" ErrorMessage="Enter a number." Display="Dynamic" ValidationGroup="Group2" />
<asp:CompareValidator id="compareValidator" runat="server" ControlToValidate="textBox2" ControlToCompare="textBox1" Type="Double" Display="Dynamic" Operator="LessThan" Text="Error." ValidationGroup="Group3" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate()" />
In Javascript
<script type="text/javascript">
function Validate() {
var isValid = false;
isValid = Page_ClientValidate('Group1');
if (isValid) {
isValid = Page_ClientValidate('Group2');
}
if (isValid) {
isValid = Page_ClientValidate('Group3');
}
return isValid;
}
</script>
I think you should use Custom Validator for second textbox to confirm that Comparison logic occurs if regular expression validation passes. You could do it the following way-
<asp:Textbox id="textBox2" runat="server" text=""></asp:Textbox>
<asp:CustomValidator id="CustomValidator2" runat="server"
ControlToValidate = "textBox2"
ErrorMessage = "Your Error Message"
ClientValidationFunction="validateLength" >
</asp:CustomValidator>
<script type="text/javascript">
function validateLength(oSrc, args){
// your validation logic here
}
</script>

Custom validator on asp page returns Page.IsValid (ture) even when invalid entry

I have a piece of code which i need to fix.
<td>
<asp:TextBox ID="txtEmail" runat="server" CssClass="TextBoxCss"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqEmail" runat="server" ControlToValidate="txtEmail"
ErrorMessage="Enter Email" ValidationGroup="entryvalid" Display="None">
</asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender4" runat="server"
TargetControlID="reqEmail" CssClass="CustomValidator" />
<asp:CustomValidator ID="valEmail" ControlToValidate="txtEmail" Display="None"
runat="server" ValidationGroup="entryvalid" ErrorMessage="Invalid Email Address"
ClientValidationFunction="ValidateEmail" />
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server"
TargetControlID="valEmail" CssClass="CustomValidator" />
</td>
If i am leaving email box empty then it says "enter mail" and page.IsValid is returning False using the below code:
public bool IsValid
{
get
{
EnableValidation(true);
Page.Validate("entryvalid");
return Page.IsValid;
}
}
EmailValidation func :
function ValidateEmail(source, arguments) {
var val1 = $.trim(arguments.Value.toLowerCase());
var regexemail = /^([\w-_]+\.)*[\w-_]+#([\w-_]+\.)*[\w-_]+\.[\w-_]+$/;
arguments.IsValid = regexemail.test(val1);
}
But when i give invalid email ("user#gmail#.com") it says "Invalid Entry" but Page.IsValid is returning True.
Can anyone please mention where might be wrong?
I use this for email validation:
<asp:RegularExpressionValidator ID="valEmail" runat="server"
ErrorMessage="* Please enter a valid email address"
ControlToValidate="txtEmail"
ValidationGroup="Group1"
ValidationExpression="^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$">
</asp:RegularExpressionValidator>
This is client side validation rather than server side validation
EDIT
Currently the server does not know if the custom validator is valid or not.
You need to add: OnServerValidate="ServerValidation" to the custom validator in the aspx.
Then add the following server side:
void ServerValidation (object source, ServerValidateEventArgs arguments)
{
//perform your check here.
arguments.IsValid = false;
}
Now when Page.IsValid is called, the server will know about the custom validator.
See this article
Try this Aspx code:
<asp:RequiredFieldValidator runat="server" ID="rfvEmail" Display="None" ControlToValidate="txtEmail"
InitialValue="" ValidationGroup="SubscriptionDetails" ErrorMessage="Email is Mandatory"
ForeColor="Red"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceEmail" TargetControlID="rfvEmail" runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
ControlToValidate="txtEmail" ErrorMessage="Invalid Email" ValidationGroup="SubscriptionDetails"
Display="None"></asp:RegularExpressionValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vce1Email" TargetControlID="regexEmailValid"
runat="server">
</ajaxToolkit:ValidatorCalloutExtender>

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

custom validator is not working in 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>

Asp.Net End date greater than start date

Work on Asp.Net vs 08.
Below is my code
<asp:TextBox ID="txtSTART_DATE" runat="server"></asp:TextBox>
<cc1:PopupControlExtender ID="txtSTART_DATE_PopupControlExtender" runat="server" CommitProperty="value"
CommitScript="e.value += '';" PopupControlID="pnlSTART_DATE"
Position="Bottom" TargetControlID="txtSTART_DATE">
</cc1:PopupControlExtender>
<asp:TextBox ID="txtEND_DATE" runat="server"
ontextchanged="txtEND_DATE_TextChanged"></asp:TextBox>
<cc1:PopupControlExtender ID="txtEND_DATE_PopupControlExtender" runat="server" CommitProperty="value"
CommitScript="e.value += '';" PopupControlID="pnlEND_DATE"
Position="Bottom" TargetControlID="txtEND_DATE">
</cc1:PopupControlExtender>
C# syntax is
protected void dtpSTART_DATE_SelectionChanged(object sender, EventArgs e)
{
AjaxControlToolkit.PopupControlExtender.GetProxyForCurrentPopup(this.Page).Commit(dtpSTART_DATE.SelectedDate.ToString("dd MMM yyyy"));//Set the value
}
protected void dtpEND_DATE_SelectionChanged(object sender, EventArgs e)
{
AjaxControlToolkit.PopupControlExtender.GetProxyForCurrentPopup(this.Page).Commit(dtpEND_DATE.SelectedDate.ToString("dd MMM yyyy"));//Set the value
}
want to compare start date with the end date.Verify that end date greater than start date and today date.How to check the value?
You could use the asp.net CompareValidator, e.g.
<asp:TextBox ID="txtSTART_DATE" runat="server" />
<asp:TextBox ID="txtEND_DATE" runat="server" />
<asp:CompareValidator ID="cmpDates" ControlToValidate="txtEND_DATE"
ControlToCompare="txtSTART_DATE" Operator="GreaterThan" Display="dynamic"
ErrorMessage="End date must be after start date" runat="server" />
This won't do a popup though, but if you are just after a validator then that should be ok.
The compare validator is actually very powerful, for instance, you can check the datatype of the argument as well, so I would use something like this:
<asp:TextBox ID="txtSTART_DATE" runat="server" />
<asp:CompareValidator ID="chkStartIsDate" runat="server" Display="Dynamic"
Operator="DataTypeCheck" Type="Date" ControlToValidate="txtSTART_DATE"
ErrorMessage="You must supply a valid start date" />
<asp:TextBox ID="txtEND_DATE" runat="server" />
<asp:CompareValidator ID="chkEndIsDate" runat="server" Display="Dynamic"
Operator="DataTypeCheck" Type="Date" ControlToValidate="txtEND_DATE"
ErrorMessage="You must supply a valid end date" />
<asp:CompareValidator ID="cmpStartAndEndDates" runat="server" Display="Dynamic"
Operator="GreaterThan" ControlToValidate="txtEND_DATE" ControlToCompare="txtSTART_DATE"
ErrorMessage="The end date must be after the start date" />
<asp:TextBox ID="txtStartDate" runat="server" />
<asp:TextBox ID="txtEndDate" runat="server" />
<asp:CompareValidator ID="cvStartEnd" Operator="GreaterThan" Type="Date"
ControlToValidate="txtEndDate" ControlToCompare="txtStartDate"
ErrorMessage="End date must be greater than start date!" runat="server"/>
Make sure to set property Type="Date" otherwise it would do a string compare and give u wrong results.

Resources