Validating mandatory fields in C# using Asp.net technology is essential for

Recently, I started exploring ASP.NET.

In my project, there are three ASP controls: a textbox, a dropdown, and a submit button.

The requirement is that if the dropdown option is selected, then the textbox should be a mandatory field. However, if no dropdown option is selected, then the textbox should not be mandatory. Currently, I am facing an issue where the required field validator still triggers even when no dropdown option is selected.

To address this challenge, I have implemented a JavaScript solution to check if the textbox is empty and disable the required field validation accordingly.

<td><label for="schoolName">SCHOOLNAMES</label></td>
   <td><asp:TextBox ID="txtschoolname" runat="server"></asp:TextBox>
       <asp:RequiredFieldValidator ID="RequiredFieldValidatorSchoolName"            runat="server" 
        ControlToValidate="txtschoolname" ForeColor="Red"   
       ErrorMessage="Required"></asp:RequiredFieldValidator>
   </td>
<td>Bank Name</td>
        <td>
          <select">
              <option>Please select the bank</option>
              <option value="DBN">DBN</option>
              <option value="CCC">CCC</option>
          </select>
        </td>

<td colspan="2">
        <asp:Button ID="Button1" runat="server" Text="submit"  
            OnClientClick=" validate();" onclick="Button1_Click"   />

JavaScript:

function validate() {
    var txt = document.getElementById("txtschoolname");
    alert(txt);
    var ddlObj = document.getElementById("<%=txtschoolname.ClientID%>");
    var validatorObject = document.getElementById("<%=RequiredFieldValidatorSchoolName.ClientID%>");

    alert(ddlObj);
    if (txt == null) {
        validatorObject.enabled = false;
        //  validatorObject.isvalid = true;
    }
}

Answer №1

Discover this helpful resource: https://msdn.microsoft.com/en-us/library/Aa479045.aspx

Explore the client side API's section, which mentions utilizing the ValidatorEnable method for enabling or disabling the validator:

ValidatorEnable('<%= RequiredFieldValidatorSchoolName.ClientID %>', true); //enable

Answer №2

Using javascript is one way to accomplish this task.

If you're looking for a solution, check out the following detailed response on Stack Overflow regarding validation with checkboxes: Validation with checkbox. This method also covers cases where javascript may be disabled.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You cannot transform a lambda expression with a statement body into an expression tree

Find an employee: { Extract the email prefix from employee's login name. Check if: - Employee has a non-empty login name, - Employee is active, - ...

Creating a unique 3D model through specified coordinates with the use of THREE.js

I possess an array consisting of (x,y,z) vertices coordinates as well as a facets array that stores the indexes of vertices (taken from the first array) for each facet. Each facet may have a varying number of vertices. Is there a way to construct a unique ...

What is the best way to safely store a logged-in user on the client-side?

As I delve into creating a login system for my simple social media website where users can make posts and view feeds from fellow followers, I've successfully implemented user login. Upon logging in, I'm able to retrieve the user's credential ...

Creating Bound HTML inside an AngularJS Grid Cell Template

I recently started using angular js and came across a helpful question on Conditional cell template in ui-grid angularjs. It worked perfectly for me, but now I'm curious about how to display HTML elements like a button tag instead of plain text. Whene ...

Express server experiences empty body when using the Fetch POST method

Executing a POST request from my browser client looks like this: const post = async (url, body) => { try { const response = await fetch(url, { method: `POST`, headers: { 'Conte ...

Issues persist with redirection when using AJAX and PHP in a login form, resulting in the user staying on the index page

After filling out both the email and password form fields and clicking the sign-in button, my script is functioning correctly. However, upon clicking the sign-in button, I want the user to be redirected to the home page. Currently, the user remains on the ...

Obtain parent class as either first or second option

I am facing a challenge with the following code snippet: <form class="row" id="testamentExecutor"> <div id="executorsSection" class="form-row"gt; <div class="executorSection form-row&q ...

Failure on a segment of the function prevents success from being achieved

I have a pair of text input fields, and I've written an onkeyup function that sends the input data to another page named "jsonpage.html" when the user starts typing. However, the success part of my code isn't working as expected. It seems to be h ...

Issue with loading JS while trying to create and edit an element

I am seeking assistance with two issues I am facing in the execution of my JavaScript code. The first problem arises when working with the 'change' and 'select' events to detect selections and changes within a dropdown menu. Specificall ...

Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me? <!DOCTYPE html> <html lang=& ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Calculate the number of elements in a given array within a specific document

I'm in the process of setting up a blog where each post consists of multiple paragraphs. My goal is to be able to count the number of paragraphs in a specific post. The structure of my "Blog" collection, which contains documents (posts), looks like th ...

JavaScript: experiencing difficulty incorporating API string into JSON format

When I am trying to add values to a JSON object manually, it works fine: Code: for (var k = 0; k < result.length; k++) { result[k]["sender"] = k; } https://i.sstatic.net/jnbpw.png However, when I fetch values from an API and att ...

CSS Fixed Header in Gridview disappears when 'Edit' link is hovered over, causing scrolling to occur

Browser - Internet Explorer 9 Utilizing the most recent version of Microsoft's AdventureWorks2012 sandbox database (AdventureWorks2012_Data.zip) for SQL related data. No C# page utilized behind the scenes To start with, there are no issues with the ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Accessing iPhone photo galleries through web browsers using HTML5 technology

I'm looking for a way to interact with the camera roll and photo library on iPhone/iPad using only HTML5 and JavaScript in the browser. I want to create a web app without relying on PhoneGap at this stage. Currently, I can capture a picture from the ...

Incorporating a static array into IEnumerable

The following method retrieves the data in the specified format: IEnumerable<object[]> - where each array contains a set number of elements (representing a relational data structure). DataEnumerable.Column[] - includes metadata columns, most likel ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

Monitoring all HTTP requests in Asp.net for health reasons

Hello there, I am interested in keeping a record of all requests generated within a website, even including any http requests that fail. Is there a way to achieve this? For instance, I would like to monitor all http requests made from the site, including ...

Creating interactive click and model expressions in AngularJS

Within my ng-repeat loop, I am trying to implement the following toggle functionality: <a href='#' ng-model="collapsed{{$index}}" ng-click="collapsed{{$index}}=!collapsed{{$index}}">{{item.type}}</a> <div ng-show="collapsed{{$in ...