How to create function to validate dropdownlist in the backend

javascript validation for dropdownlist selection
dropdown validation in jquery
dropdown validation in javascript w3schools
how to validate dropdownlist in jquery on button click
how to validate select option in javascript
how to validate select option in jquery
javascript validation for dropdownlist in asp.net c#
dropdown required validation in html

I am developing a small form with the help of C# and ASP.NET MVC and within this form I have a dropdownlist which shows some enabled states this depends on the value that comes in the form that in this case would be FINISHED.

I would like to place some restriction from the back-end to avoid that if the users change the values ​​of disabled from the console of the navigator, it does not allow him to send them, what I really need is to validate in the controller that this data is not sent.

The following is the code dropdownlist with its different options

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<select id="ticketStatusInput" name="status" class="form-control form-control-user" style="width: 100%; padding: 0.375rem 0.75rem; height: 50px;" tabindex="-1" aria-hidden="true">
<option value="" disabled="" selected="">Select a option</option>
<option value="ABT" disabled="">OPEN</option>
<option value="ASG">ASSIGNED</option>
<option value="CDO" disabled="">CLOSED</option>
<option value="ESU" disabled="">WAITING FOR USER</option>
<option value="PRC">IN PROCESS</option>
<option value="TMN">FINISHED</option>
</select>

You can use this method also.

If you want more validation you can create Custome validation also.

You can get all disable the option in the database then you check if you want to prevent static data compression.

[HttpPost]
public JsonResult UpdateTicketFromDetails()
{
    var ticketStatusInput = Request.Form["ticketStatusInput"];

    var ticketStatusInput = Request.Form["ticketStatusInput"];
    var oExcludeItem = new string[] { "ABT", "CDO", "ESU" }; // You can use string array also   
    if (!string.IsNullOrEmpty(ticketStatusInput))
    {
        if (oExcludeItem.Contains(ticketStatusInput))
        {
            return Json(new TicketResult
            {
                IsValid = false,
                Error = "Please select only enable option";
             });
        }
    }
    else
    {
        return Json(new TicketResult
        {
            IsValid = false,
            Error = "Please select valid data";
       });
    }
    var lstDisableOption = new List<string>(); // You can also use with List object
    lstDisableOption.Add("ABT");
            lstDisableOption.Add("CDO");
            lstDisableOption.Add("ESU");
            if (!string.IsNullOrEmpty(ticketStatusInput))
            {
                if (lstDisableOption.Any(x => x == ticketStatusInput))
                {
                    return Json(new TicketResult
                    {
                        IsValid = false,
                        Error = "Please select only enable option";
                    });
                 }
            }
            else
            {
                return Json(new TicketResult
                {
                    IsValid = false,
                    Error = "Please select valid data";
                 });
             }
        }

    try
    {
        TicketRegisterResult result;
        using (var scope = new TransactionScope())
        {
            // I create a new record variable with all fields
            var record = new TK_DT_RECORDS
            {
                TK_CT_STATUS_ID = ticketStatusInput,
            };
            // We update the ticket data (this will always be done)
            var model = new TicketRegisterModel();
            // We create the new record in the record table and insert it
            result = model.UpdateTicket;

            //If the ticket was not saved, the transaction is finished and we return the error message
            if (!result.Success)
                return Json(new TicketResult
                {
                    IsValid = false,
                    Error = "The changes could not be saved, please try again."
                });
            scope.Complete();
        }
    }
    catch (DbEntityValidationException ex)
    {
        //Failed to try to register data in the database
        foreach (var e in ex.EntityValidationErrors)
            foreach (var validationError in e.ValidationErrors)
                Console.WriteLine("Property: " + validationError.PropertyName + " Error: " +
                                  validationError.ErrorMessage);

        return Json(new TicketResult
        {
            IsValid = false,
            Error = "There was an error creating the ticket, please try again."
        });
    }
    return Json(new TicketResult
    {
        IsValid = true
    });
}

how to validate a dropdownlist using javascript?, using jQuery you can do it in this way. function validateRadio() { var flag = false; $('#<%=RadioButtonList1. ClientID%> input'). each(function(){ if($(this).is(":checked")) flag = true; }); return flag; } function validateDropList() { if ($('#<%=DropDownList1. Open the window of data validation and select the list in the drop down of Allow. Click in the text box of the source (or click on the small sub arrow on the right side). Select the list that contains the list of Criteria. (If only select list using arrow then Click on the down arrow on the right side of the small window).


It may be not that optimal solution, but you can make the same request as in your ajax call in your controller via HttpClient. Parse the response data and compare with the data that comes from the UI. If selection from the UI doesn't comply to rules - throw error.

Here is a bit of code that can show the idea:

// Define InputStatus enum, which represents all available statuses

public async Task<InputStatus> GetValidInputStatus(string url)
{
    var httpClient = new HttpClient(); // or better inject it into controller
    var httpReq = new HttpRequestMessage();

    httpReq.Method = HttpMethod.Post;
    httpReq.RequestUri = new Uri(url);

    var response = await httpClient.SendAsync(httpReq);
    var content = await response.Content.ReadAsStringAsync();

    // Parse content string somehow into an InputStatus
    InputStatus validStatus = ParseStatus(content);

    return validStatus;
}

[HttpPost]
public Task<JsonResult> UpdateTicketFromDetails()
{
    var ticketStatusInput = Request.Form["ticketStatusInput"]; // Convert it to InputStatus model somehow
    var validStatus = await GetValidInputStatus(url); // Put here the same url as in your ajax call on the UI

    if (validStatus == InputStatus.TMN && 
        (ticketStatusInput == InputStatus.ABT || ticketStatusInput == InputStatus.CDO || ticketStatusInput == InputStatus.ESU))
    // throw, user sent disabled statuses
    else
    // continue
}

DropDownList Validation: Validate DropDownList using JavaScript , Now here in this tutorial, I'll explain how to validate dropdownlist from Function To Validate Asp.net DropDownList Control – [JavaScript]. To create the data validation list on the Dashboard sheet, start by going to the Data tab on the Ribbon and clicking on the Data Validation icon, which looks like this: This will bring up the Data Validation window .


Your question is when you load form with data (finished state), your dropdown should be only available to select assigned or in progress.

Then user sends update request, you should validate, user send values only between in those two, when original data in finished.

This is not the complete code, but the solution.

var ticketStatusInput = Request.Form["ticketStatusInput"]; 
var idOfOriginalData = Request.Form["id"]; 

//// get the correct or original data. here i uesd get back from database, you can use sessions, viewdata, tempdata 
var originalObj = GetOriginalFromDatabase(idOfOriginalData);

//// then only you can do the validation. 
if ( originalObj.State == "TMN")
{
    var expetedOptions = new string[] { "ASG", "PRC"};

    //// check status that user sent is in expetedOptions
    if ( !expetedOptions.Contains(ticketStatusInput))
    {
        return Json(new TicketResult
        {
            IsValid = false,
            Error = "Please select only enable option";
         });
    }
}

Dropdownlist Validation using JavaScript in HTML, Asp.net, Here I will explain how to validate dropdownlist using JavaScript in To validate dropdownlist first we need to get selected value of function ValidateDropdown​() { NET Framework · Simple login form example in asp.net Check Username and Password availability in database Asp.Net MVC Tutorial. In this article I will explain how to validate (check) HTML Select DropDownList using JavaScript and jQuery. Validate (Check) HTML Select DropDownList using JavaScript The following HTML Markup consists of an HTML Select DropDownList and a Button.


If I understood your question correctly, this might help. This is just a proof of concept.

Create object model of StatusTypes

public class StatusTypes{
public string Key { get; set; }
public string Value { get; set; }
}

Declare variables inside the class

public List<StatusTypes> AllowedStatusTypes { get; set; }
public List<StatusTypes> AllStatusTypes { get; set; } = GetAllStatusTypes();

Here is the function placeholder for getting all status types

public static List<StatusTypes> GetAllStatusTypes()
{
var list = new List<StatusTypes>();
// list = call method/url here to get all types
return list;
}

Call this method at the same time you are loading options from database for the "data"

public void UpdateAllowedTicketStatusTypes(string statusID)
{
switch(statusID){
    case "TMN":
        AllowedStatusTypes = AllStatusTypes.Where(o => o.Value == "ASG" || o.Value == "PRC").ToList();
        break;
    default:
        AllowedStatusTypes = AllStatusTypes;
        break;
}    
}

Then inside your UpdateTicketMethod, you can do this check

if(ticketStatusInput == "TMN" && (AllowedStatusTypes.Exists(o => o.Value == "ABT") || AllowedStatusTypes.Exists(o => o.Value == "CDO") || AllowedStatusTypes.Exists(o => o.Value == "ESU"))){
return Json(new TicketResult{
    IsValid = false,
    Error = "Please select valid value."
});
}

Validate (Check) HTML Select DropDownList using JavaScript and , Inside the function, the HTML Select DropDownList object is referenced and if the selected value matches the value of the default item then an error message is  Introduction: In previous articles i explained How to implement Jquery form validations in asp.net and Example to validate asp.net CheckBoxList using jQuery and jQuery to validate file extension and upload image file in asp.net and jQuery stylish dropdown menu example like Facebook,Linkedin and jQuery to Validate email address using RegularExpression and Create drop down menu for login and


How to create function to validate dropdownlist in the backend, I am developing a small form with the help of C# and ASP.NET MVC and within this form I have a dropdownlist which shows some enabled  Before Adding the salary of Employee, I had to Select Month from the Drop Down List. The list of the Month are stored in databases. if the month is not selected and user press Create Button the program should display the message that no Month is selected.


Check if User has Selected any Value from HTML SELECT Element , It is easy to check if a user has selected value from an HTML Select element using Asp.Net provides a similar control in the form of a DropDownList to web developers. procedures, for data validation, if you are submitting the data in a database. AngularJS forEach() Function – Iterate or Loop Through Each Item in An  the text were added to the dropdown list, however, whenever I select an item to the dropdown list, nothing is selected. only blank is selected. when i used the first code: //populate dropdown based on multiple textbox. var aValues = this.getField("LstGrp").getArray().map(function(a){return a.valueAsString;});


Handling select box (drop-down list) in a PHP form, This tutorial will show you how to add select boxes and multi-select boxes to a to validate the data, and how to take different actions depending on the input. The second method is just passing the selected value to the header function to  Angular 8/9 Custom Validation for Select Dropdown using Reactive Forms. To validate the select dropdown in Angular 8, we need to import Validators class with Reactive Forms. I am also going to create a custom validators function for select dropdown validation using Reactive forms, we can also use this custom validator to validate other Form elements as well. Go to app.component.ts file and add the following code.