validation on a usercontrol on aspx page using javascript - c#

I have a user control that contains 3 dropdown for(date,month, year).I have called this user control on aspx page.
Please select Date From.
On my aspx page all fields are validated with javascript validation.
when I select date from this user control (not month & year) ,and click on submit button, it shows the error message.
but my problem is that if i select year (not date,month) then in this case neither it fire the error message nor it saves the data.
I want that it fired the message everytime when atleast one field(day,month,year) is not selected.I want to handle this problem on clentside. Please give me your suggetion.
function InputValidation(vg) {
var isValid = true;
try {
var j = 0;
var inputCtrlArr = new Array();
var key = 'block';
var inputIntputArr = document.getElementsByTagName('input');
var inputDdlArr = document.getElementsByTagName('select');
var inputTextareaArr = document.getElementsByTagName('textarea');
var c = 0;
for (var i = 0; inputIntputArr.length > i; i++) inputCtrlArr[c++] = inputIntputArr[i];
for (var i = 0; inputDdlArr.length > i; i++) inputCtrlArr[c++] = inputDdlArr[i];
for (var i = 0; inputTextareaArr.length > i; i++) inputCtrlArr[c++] = inputTextareaArr[i];
for (var i = 0; inputCtrlArr.length > i; i++) {
if (inputCtrlArr[i].getAttribute('required') == 'true' && inputCtrlArr[i].getAttribute('vg') == vg) {
if (inputCtrlArr[i].value.trim() == '') {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
if (inputCtrlArr[i].type == "checkbox") {
if (inputCtrlArr[i].checked == false) {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
}
var errorDivId = inputCtrlArr[i].getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
}
}
catch (ex) { }
}
function InputCntrlValidate(obj) {
try {
if (obj.getAttribute('required') == 'true') {
if (obj.value == '') {
key = 'block';
}
else {
key = 'none';
}
var errorDivId = obj.getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
} catch (ex) { }
}
function sanitizeInput(obj) {
if (obj.getAttribute('msg') == obj.value) {
alert("same value");
}
}

The problem is in your JavaScript. Since if it is working for the one dropdownlist then it should work for other two. Further you will have to check for month and date. If it is feb then the days should be 28 or 29 and it will depend on the year. So lots of effort will require to solve it.

You only need three RequiredFieldValidators with each ControlToValidate leading to one of your DropDownLists. If you've a default value of f.e. "please select" you should set this as InitialValue of the Validators.
Here is a sample(i've only added few ListItems instead of all for dates,months and years):
<asp:DropDownlist ID="DdlDate" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
<asp:ListItem Text="3"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqDate"
ControlToValidate="DdlDate"
InitialValue="please select"
ErrorMessage="Please select Date"
Display="Dynamic"
runat="server">
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlMonth" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="January"></asp:ListItem>
<asp:ListItem Text="February"></asp:ListItem>
<asp:ListItem Text="March"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqMonth"
ControlToValidate="DdlMonth"
InitialValue="please select"
ErrorMessage="Please select Month"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlYear" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="2010"></asp:ListItem>
<asp:ListItem Text="2011"></asp:ListItem>
<asp:ListItem Text="2012"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqYear"
ControlToValidate="DdlYear"
InitialValue="please select"
ErrorMessage="Please select Year"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:Button ID="BtnSubmit" runat="server" Text="submit" />

I would use the calendar control on the AjaxControlToolKit if it were me. No validation required then other than if the field is mandatory. It's a lot easier and looks a lot better. All client side.
Just down load the ajxcontrolkit dll and include in your project and use as per any custom control/third party component.
EDIT:
Ok if you just want at least one drop down to be selected then try JQuery e.g.
function isDropDownsValid()
{
var isValid = true;
$('select').map(function()
{
if($(this).val() == -1)
{
isValid = false;
}
});
return isValid;
}
Then wire into your submit button like so
<asp:Button ID="myButton" runat="server" OnClientClick="return isDropDownsValid" Text="Submit />
Here is a fiddle with a demo. You may need to change the selector $('select') to target the exact dropdowns you need.

Related

About RadioButtonList in ASP.NET

I have a RadioButtonList. I want the button to be available when I click "Agree", and not available when I click "Disagree". Default is disabled.
Now whether I agree or disagree, my btnSubmit button will become available. And it won't change back to unavailable.
function acceptprotocol() {
if (document.getElementById("rblAccept").SelectValue == 0 {
document.getElementById("btnSubmit").disabled = true;
}
else {
document.getElementById("btnSubmit").disabled = false;
}
}
RadioButtonList:
<asp:RadioButtonList ID="rblAccept" runat="server"
RepeatDirection="Horizontal" style="margin:auto"
onclick="acceptprotocol()">
<asp:ListItem Value="0">Agree</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Against</asp:ListItem>
</asp:RadioButtonList>
How to solve it? Please help me.
Here's the code snippet for your solution:
RadioButtonList:
<asp:RadioButtonList ID="rblAccept" runat="server" RepeatDirection="Horizontal" style="margin:auto"
onclick="acceptprotocol()">
<asp:ListItem Value="0">Agree</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Disagree</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Enabled="false" />
Function:
function acceptprotocol() {
var radioButtonAccept = document.getElementById('<%=rblAccept.ClientID %>').getElementsByTagName("input");;
for (var i = 0; i < radioButtonAccept.length; i++) {
if (radioButtonAccept[i].checked) {
if (radioButtonAccept[i].value == 1) {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = true;
}
else {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = false;
//use this bellow line if you want the after enable button button will availble all time
document.getElementById('<%=rblAccept.ClientID %>').removeAttribute("onclick");
}
break;
}
else {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = true;
}
}
}

Stopping user entering numerical value in a texbox when using C#

I am trying to stop the user to enter a numerical value in the search criteria text box when the Dropdown value is MBID The code works I only need help on how to resolve the validation issue
C# Code
protected bool searchData()
{
string val = DropDownList1.SelectedItem.Value;
switch (val)
{
case "MBID":
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT count(*)
from Patient where MBID = #SearchCriteria ", con))
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
int userCount = (Int32)cmd.ExecuteScalar();
da.Fill(dt);
}
}
}
}
The Search button call the code below
protected void btnSearch_Click(object sender, EventArgs e)
{
if (FormValidation()) if (searchData())
{
BindGrid();
inputUpdateFornData();
}
}
HTML Code
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="MBID">MBID</asp:ListItem>
<asp:ListItem Value="HPNumber">HP Number</asp:ListItem>
<asp:ListItem Value="NHSNumber">NHS Number</asp:ListItem>
I cannot used the code below because numerical value can be entered for the other option of the dropdown
<asp:TextBox ID="txtSearchCriteria" runat="server />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtSearchCriteria" Type="Integer"
Operator="DataTypeCheck" ErrorMessage="Value must be an integer!" />
This is how to do it:
try
{
int d = int.Parse(txtSearchCriteria.Text);
//if works str is a number
}
catch (Exception e)
{
Console.WriteLine("It isn't a number!");
}
Add ClientValidationFunction="validateFunction" in your CompareValidator.
And write validation function as follows-
function validateFunction(s,args){
if (yourdropdown.value == "MBID")
{
// Your code
}
}
If you want server validation , add OnServerValidate attribute and handler function on server side.
hello please try below code for javascript validation
below is javascript code
<script>
function validateSearch()
{
var dropdown = document.getElementById("<%= ddlSearch.ClientID %>");
var txtSearch = document.getElementById("<%= txtSearch.ClientID %>");
if (dropdown.value == "MBID")
{
var reg = /^\d+$/;
if (!reg.test(txtSearch.value)) {
alert("Please enter proper value");
txtSearch.focus();
return false;
}
}
}
</script>
and below is aspx code of dropdown and textbox.
<asp:DropDownList runat="server" ID="ddlSearch">
<asp:ListItem Text="Select" Value="-1"></asp:ListItem>
<asp:ListItem Text="MBID" Value="MBID"></asp:ListItem>
<asp:ListItem Text="Name" Value="Name"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:Button runat="server" ID="btnSearch" Text="Search" OnClientClick="return validateSearch();" />

ASP.net Dynamic Dropdown Validation

This seems like a reasonably common question, however the equally common solutions don't appear to work. Essentially the required validation control of the drop-down menu isn't firing. The drop down is populated dynamically, the code that populates the drop-down is shown at the bottom of the page.
<asp:DropDownList ID="Event" runat="server"DataTextField="EventTime" ValidationGroup="DD"
DataValueField="EventID" SelectMethod="GetEvents" AppendDataBoundItems="true" AutoPostBack="true">
<asp:ListItem Text="Select..." Value="-1" /></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldEvent" runat="server" ControlToValidate="Event"
Display="Dynamic" ValidationGroup="DD" InitialValue="-1" AutoPostback="true"
ErrorMessage="Please select a time"></asp:RequiredFieldValidator>
Code Behind:
public IQueryable<Event> GetEvents([QueryString("bikeID")] int? bikeId)
{
var _db = new WLL.DAL.Context();
IQueryable<Event> query = _db.Events;
if (bikeId.HasValue && bikeId > 0)
{
query = query.Where(b => b.BikeID == bikeId);
}
else
{
query = null;
}
return query;
}
Set InitialValue = "0" .This worked for me when -1 did not work.

How to change the label at the time of radio button selection is changed using asp.net?

here is my following stuff in asp.net
<asp:RadioButtonList ID="RbList" runat="server"
onselectedindexchanged="RbList_SelectedIndexChanged">
<asp:ListItem Text="Male" Value="1"></asp:ListItem>
<asp:ListItem Text="Female" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<asp:Label ID="lbltest" runat="server"></asp:Label>
and here is my RBList_SelectedIndexChanged event.
int i = RbList.SelectedIndex;
if (i == 1)
{
lbltest.Text = "You have click on male";
}
if (i == 2)
{lbltest.Text = "You have click on female";}
Now, I want when item 1 is selected the text lable must be according to the selected item of radiobutton list.
How could be this is possible?
Regards.
Set Autopostback="true" on RbList
change your code to the following:
int i = RbList.SelectedIndex;
if (i == 0)
{
lbltest.Text = "You have click on male";
}
else if (i == 1)
{ lbltest.Text = "You have click on female"; }

How to get the Text of the Radiobuttonlist?

<asp:RadioButtonList ID="rbl" runat="server" onMouseUp="Myf()">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
function Myf() {
var list = document.getElementById("<%=rbl.ClientID %>");
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].innerHTML);
}
}
I'm getting the value of Radiobuttonlist. How to get the Text of the Radiobuttonlist?
First of all the radio buttons do not have text in your code
Second, if you look at the source of the resulting html page, you can see that the radio buttons have labels that store the text.
So you can look for label instead of input in your function and it will get the text
function Myf() {
var list = document.getElementById("<%=rbl.ClientID %>");
var inputs = list.getElementsByTagName("label");
var selected;
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].innerHTML);
}
}
Use the getAttribute() method.
element.getAttribute("Text");
More info on: https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute?redirectlocale=en-US&redirectslug=DOM%2Felement.getAttribute
To get text you have to put "label" instead of "input" in getelement.
try like this:
var inputs = list.getElementsByTagName("label");
<asp:RadioButtonList ID="rbl" runat="server">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
$(document).ready(function () {
$('[id*="rdl"],[type="radio"]').change(function () {
if ($(this).is(':checked'))
console.log($(this).next('label').html());
});
});
try this
function Myf() {
$("#<%=rbl.ClientID %>").find('input').each(function () {
var this_input = $(this);
alert($("#<%=rbl.ClientID %>").find('label[for="' + this_input.attr('id') + '"]').text());
})
}

Categories

Resources