ASP.net Validation for RadioButton - asp.net

I want validation like, if i select Status as Reject then there must be some Comments(compulsory). and if status is Accept then comments may be blank (not compulsory)
How I will do it in ASP.NET, Please find my code
<tr>
<td width="30%">
<b>Status:</b>
</td>
<td>
<asp:RadioButton ID="lAccept" runat="server" AutoPostBack="True"
CausesValidation="True" Text="Accept" />
<asp:RadioButton ID="lReject" runat="server" AutoPostBack="True"
CausesValidation="True" Text="Reject " />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ErrorMessage="Please Select it is Accepted or Rejected" ForeColor="Red"></asp:RequiredFieldValidator>
</tr>
<tr>
<td width="30%">
<b>Qty Rejected:</b>
</td>
<td>
<asp:TextBox ID="lRejectedQty" runat="server" CausesValidation="True"></asp:TextBox>
<%-- <asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Only interger between 1 to 10000000 " ondisposed="Page_Load"
oninit="Page_Load" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>--%>
<asp:RangeValidator ID="RangeValidator3" runat="server"
ErrorMessage="Rejected Quantity must be in change of 1 to 10,000,000"
ControlToValidate="lRejectedQty" Display="Dynamic" ForeColor="Red"
MaximumValue="10000000" MinimumValue="1"></asp:RangeValidator>
</td>
</tr>
<tr> <td width="30%">
<b>Comments:</b>
</td>
<td>
<TEXTAREA rows=5 cols=40 name="lComments" id="lComments"></TEXTAREA>
</td>

The simplest way for this is to use a CustomValidator.
MSDN: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator(v=vs.110).aspx
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="You must enter Comments if you choose to Reject."
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
Then in your code-behind you may do more detailed checks for it being valid or not
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = true; // set it to be valid by default
if (lReject.Checked == true && string.IsNullOrWhiteSpace(lComments.Text) == true)
{
// Reject was selected and no comments were entered
e.IsValid = false;
}
}
The drawback is that this requires a PostBack to the server and will validate after the other types in most cases.

Related

Textboxes and Dropdown appearing when visibility set to false

We have a page that allows users to update data using about a dozen textboxes and several dropdowns. Half of all the fields are permanently visible and the rest are hidden. If a checkbox is checked, the page reveals the rest of the fields.
When first arriving on the page, the two textboxes and dropdown in question are not visible, along with the rest of the fields not visible, unless the checkbox is checked.
However, with the update functionality (a button click) the two textboxes and dropdown appear with the other permanently visible fields. Oddly enough, the labels corresponding to the fields that should be hidden do not appear. Another point is that, if the checkbox is checked and then unchecked, the fields in question are not visible.
So it appears that the issue is with the update functionality but we haven't been able to pinpoint what the issue is. We have tried setting the visibility to false in the .ascx.cs file but that has had zero effect along with other things we've tried.
Is there anything obvious we might be missing from our code below?
ascx:
<asp:FormView ID="FormView1" runat="server" DataSourceID="odsQWER" DataKeyNames="Oid"
OnItemInserting="FormView1_ItemInserting" EnableModelValidation="true"
OnItemUpdating="FormView1_ItemUpdating">
...
<tr>
<td style="width: 200px">
<asp:Label ID="ContactFNameLabel" runat="server" Text="Vendor Contact (First Name):"
Visible="false"></asp:Label>
</td>
<td>
<asp:TextBox Width="400px" ID="ContactFNameTextBox" runat="server" Text='<%# Bind("FirstName") %>'
Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator ID="ContactFNameValidator" runat="server" ControlToValidate="ContactFNameTextBox"
Display="Dynamic" ErrorMessage="Contact Name cannot be Blank" Visible="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width: 200px">
<asp:Label ID="ContactLNameLabel" runat="server" Text="Vendor Contact (Last Name):"
Visible="false"></asp:Label>
</td>
<td>
<asp:TextBox Width="400px" ID="ContactLNameTextBox" runat="server" Text='<%# Bind("LastName") %>'
Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator ID="ContactLNameValidator" runat="server" ControlToValidate="ContactLNameTextBox"
Display="Dynamic" ErrorMessage="Contact Last Name cannot be Blank" Visible="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width: 200px">
<asp:Label ID="CountryLabel" runat="server" Text="Country:" Visible="false"></asp:Label>
</td>
<td>
<asp:DropDownList Width="405px" ID="CountryDropDownList" runat="server" AppendDataBoundItems="true"
DataSourceID="odsCountry" DataTextField="Name" DataValueField="Oid" SelectedValue='<%# Bind("CountryId") %>'
Visible="false">
<asp:ListItem Selected="true" Text="<--Select Here-->" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="CountryValidator" runat="server" ControlToValidate="CountryDropDownList"
Display="Dynamic" ErrorMessage="Country Must be Selected" InitialValue="0"></asp:RequiredFieldValidator>
</td>
</tr>
...
<asp:Button ID="UpdateButton" runat="server" CausesValidation="true" CommandName="Update" OnClick="btnUpdateClick"
CssClass="button" Text="Update" Visible='<%# true %>' />
...
<asp:ObjectDataSource ID="odsQWER" runat="server" InsertMethod="AddRequest"
TypeName="BLL.TESTRequest" SelectMethod="GetRequest" OnInserting="odsQWER_Inserting"
UpdateMethod="UpdateRequest" OnUpdating="odsQWER_Updating" OnInserted="odsQWER_Inserted"
OnUpdated="odsQWER_Updated" OldValuesParameterFormatString="{0}">
...
aspx:
protected void btnUpdateClick(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)FormView1.FindControl("IsNewCheckBox");
FormView1.FindControl("ContactFNameTextBox").Visible = chk.Checked;
FormView1.FindControl("ContactFNameLabel").Visible = chk.Checked;
FormView1.FindControl("ContactFNameValidator").Visible = chk.Checked;
FormView1.FindControl("ContactLNameTextBox").Visible = chk.Checked;
FormView1.FindControl("ContactLNameLabel").Visible = chk.Checked;
FormView1.FindControl("ContactLNameValidator").Visible = chk.Checked;
FormView1.FindControl("StateDropDownList").Visible = chk.Checked;
FormView1.FindControl("StateLabel").Visible = chk.Checked;
}

Validation for End Date should be greater or equal to Start Date in asp.net

I'm using this code to validate two date but the validation is not working when I enter the same or after the Start Date
<asp:CompareValidator ID="dateCompareValidator" runat="server"
ControlToValidate="EndDate"
ControlToCompare="StartDate"
Operator="GreaterThanEqual" Type="Date"
ErrorMessage="The second date must be after the first one.<br /><br />">
</asp:CompareValidator>
Do i need to use the hard code ?
Aspx File:
<tr>
<td align="right">
Start Date:
</td>
<td align="left">
<telerik:RadDatePicker ID="RadDtpFromDate" runat="server" Calendar-EnableShadows="true" AutoPostBack="true"
Culture="en-IN" DateInput-DateFormat="dd-MMM-yyyy" DateInput-EmptyMessage="DD-MMM-YYYY"
ShowPopupOnFocus="true" ToolTip="Input Date" ZIndex="30001"
onselecteddatechanged="RadDtpFromDate_SelectedDateChanged" />
<asp:RequiredFieldValidator runat="server" ID="rfvFromDate" Display="None" ControlToValidate="RadDtpFromDate"
InitialValue="" ValidationGroup="FinalSave" ErrorMessage="From Date is Mandatory"
ForeColor="Red"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceFromDate" TargetControlID="rfvFromDate"
runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
<asp:CustomValidator ID="cvFromDate" runat="server" ControlToValidate="RadDtpFromDate"
Display="None"></asp:CustomValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceRadFromDate" runat="server" TargetControlID="cvFromDate">
</ajaxToolkit:ValidatorCalloutExtender>
</td>
<td align="right">
End Date:
</td>
<td align="left" colspan="2">
<telerik:RadDatePicker ID="RadDtpToDate" runat="server" Calendar-EnableShadows="true" AutoPostBack="true"
Culture="en-IN" DateInput-DateFormat="dd-MMM-yyyy" DateInput-EmptyMessage="DD-MMM-YYYY"
ShowPopupOnFocus="true" ToolTip="Input Date" ZIndex="30001"
onselecteddatechanged="RadDtpToDate_SelectedDateChanged" />
<asp:RequiredFieldValidator runat="server" ID="rfvToDate" Display="None" ControlToValidate="RadDtpToDate"
InitialValue="" ValidationGroup="FinalSave" ErrorMessage=" To Date is Mandatory"
ForeColor="Red"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceToDate" TargetControlID="rfvToDate"
runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
<asp:CustomValidator ID="cvToDate" runat="server" ControlToValidate="RadDtpToDate"
Display="None"></asp:CustomValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceRadToDate" runat="server" TargetControlID="cvToDate">
</ajaxToolkit:ValidatorCalloutExtender>
</td>
</tr>
Cs File :
if (RadDtpFromDate.SelectedDate > RadDtpToDate.SelectedDate)
{
dateCompareValidator.IsValid = False;
return;
}
Now Try this..................

add comment in membership

I want to add comment in the membership table.
I added this in my .aspx code:
<asp:CreateUserWizard ID="Register" runat="server" OnCreatedUser="RegisterUserWithRoles_CreatedUser">
<CreateUserButtonStyle />
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
<table>
<td align="right">
<asp:Label ID="RoomLabel" runat="server" AssociatedControlID="Room">Room number:</asp:Label>
</td>
<td>
<asp:TextBox ID="Room" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RoomRequired" runat="server" ControlToValidate="Room"
ErrorMessage="Room number is required." ToolTip="Room number is required."
ValidationGroup="Register">*</asp:RequiredFieldValidator>
</td>
...
This is my aspx.cs code:
protected void RegisterUserWithRoles_CreatedUser(object sender, EventArgs e)
{
TextBox comment=
(TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("Comment");
Membership.GetUser(Register.UserName).Comment = comment.Text ;
}
}
If I debug comment.Text= "What I typ in my textbox"
But if I look in the membership table comment is null
I must just use UpdateUser.
Like this:
TextBox comment=
(TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("Comment");
MembershipUser user = Membership.GetUser(Register.UserName);
user.Comment = comment.Text;
Membership.UpdateUser(user);

Putting the cursor in text box after validating in ASP.NET

I have a basic ASP.NET website which has a register page with the user name, password and email as text boxes. Only one of them, the email, has a validation which is the default email validation from ASP.NET.
After the validation, I want the cursor to be in the email textbox if the validation fails.
Currently the message is displayed but the cursor is not on the page.
<tr>
<td>
<asp:TextBox ID="txtPassword" runat="server" CssClass="cpTextBox" TextMode="Password"
TabIndex="7" ToolTip="Password must be at least six characters in length"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Please enter password" Display="None">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password must be at least six characters in length" ValidationExpression=".{6,50}"
Display="None">*</asp:RegularExpressionValidator>
</td>
<td>
<asp:TextBox ID="txtTitle" runat="server" CssClass="cpTextBox" TabIndex="11"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblVerifyPassword" runat="server" CssClass="cpLabel" Text="Verify password"></asp:Label>
<asp:Label ID="Label4" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:Label ID="lblPhone" runat="server" CssClass="cpLabel" Text="Phone"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtVerifyPassword" runat="server" CssClass="cpTextBox" TextMode="Password"
TabIndex="8"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvConfirmPassword" runat="server" ControlToValidate="txtVerifyPassword"
ErrorMessage="Please verify the password" Display="None">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvVerifyPassword" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtVerifyPassword" ErrorMessage="Please verify the password"
Display="None">*</asp:CompareValidator>
</td>
Can someone guide me on how to do this?
Regards.
For the validator control please set SetFocusOnError="true"

ValidationSummary doesn't show up

I have a few validation controls with a validationsummary.
The client side validations shows up, after the user leaves the textbox for the validation.
The server side validation shows never up.
The Validationsummary shows never up.
What I am doing wrong?
<div class="designPhotoMiddleText" id="MiddleReg" >
<asp:Panel DefaultButton="linkRegister" runat="server" ID="panRegister" >
Jetzt kostenlos registrieren:<br />
<br />
<table>
<tr>
<td style="width: 120px;">
Username:
</td>
<td>
<asp:TextBox ID="txtRegisterUsername" Width="150px" runat="server"></asp:TextBox>
<asp:CustomValidator ValidationGroup="Register" ID="valUsername" ControlToValidate="txtRegisterUsername"
OnServerValidate="IsUsernameFree" CssClass="validator"
runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator>
</td>
</tr>
<tr>
<td>
Passwort:
</td>
<td>
<asp:TextBox ID="txtRegisterPW1" Width="150px" TextMode="Password" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="Register" CssClass="validator" ControlToValidate="txtRegisterPW1" ID="valPasswordLenght" runat="server" ErrorMessage="Das Passwort muss mindestens 6 Zeichen haben."></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Passwort erneut:
</td>
<td>
<asp:TextBox ID="txtRegisterPW2" Width="150px" TextMode="Password" runat="server"></asp:TextBox>
<asp:CompareValidator CssClass="validator" ValidationGroup="Register"
ID="valPW" ControlToCompare="txtRegisterPW2" ControlToValidate="txtRegisterPW1" runat="server" ErrorMessage="Die eingegebenen Passwörter stimmen nicht überein."></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<asp:TextBox ID="txtRegisterEmail" Width="150px" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="Register" CssClass="validator" ForeColor="black"
ControlToValidate="txtRegisterEmail" ID="valMail" runat="server"
ValidationExpression=".*#.*\.(com|net|org|edu|mil|at?|de?|ch?|uk?)$"
ErrorMessage="Bitte geben Sie eine gültige EMail-Adresse ein."
Display="Dynamic"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:CheckBox ID="chkRegsiterAGBs" runat="server" />
<asp:HyperLink ID="linkAGB" Target="_blank" NavigateUrl="~/AGBs.aspx" runat="server">AGBs</asp:HyperLink> gelesen
<asp:CustomValidator ValidationGroup="Register" ID="valAGB"
OnServerValidate="IsAGBChecked" CssClass="validator"
runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:LinkButton CausesValidation="true" ID="linkRegister" CssClass="linkWhite" runat="server"
onclick="linkRegister_Click">Jetzt Registrieren</asp:LinkButton>
<asp:ValidationSummary ValidationGroup="Register" ID="sumRegister" runat="server"
HeaderText="Fehler:"
ShowSummary="true" DisplayMode="BulletList" />
</td>
</tr>
</table>
</asp:Panel>
</div>
public void IsUsernameFree(object source, ServerValidateEventArgs value)
{
string username = value.Value;
DAL.User user = DAL.UserHandling.GetUserByName(username);
value.IsValid = (user == null);
}
public void IsAGBChecked(object source, ServerValidateEventArgs value)
{
value.IsValid = (chkRegsiterAGBs.Checked);
}
Can't tell for sure from looking at the code you've posted, but are you checking the Page's IsValid property anywhere? E.g. before running any other methods?
if (Page.IsValid){
//Do additional processing
//register user etc.
}
this check will force execution of all validation controls on the page and should then trigger the display of your validation errors.
EDIT:
You need to set the ValidationGroup to 'Register' in your markup that defines the linkRegister control
`<asp:LinkButton CausesValidation="true" ID="linkRegister" CssClass="linkWhite" runat="server" OnClick="linkRegister_Click" ValidationGroup="Register">Jetzt Registrieren</asp:LinkButton>`
Also, your RegularExpressionValidator for password needs to have its ValidationExpression property set in the markup:
`<asp:RegularExpressionValidator ValidationGroup="Register"
CssClass="validator" ControlToValidate="txtRegisterPW1"
ID="valPasswordLenght" runat="server" ErrorMessage="Das Passwort
muss mindestens 6 Zeichen haben." Validationexpression="[\w+\d+]{6,}"
</asp:RegularExpressionValidator>`

Resources