Tips for verifying error messages with asp.net mvc

My form includes fields for street address, street address line 2, city, state/province, zip code, and country. I'm having trouble validating the error message upon leaving the form.

I attempted to use [Required(ErrorMessage="Field is required")] on the Model, but it wasn't successful. The goal is to highlight all mentioned fields in red, and when leaving the State/Province field, validate with the error message "Field is required". Below is my current attempt at achieving this in the code:

// Model class
[Required(ErrorMessage = "This field is required")]
public string State { get; set; }

View.cshtml

<div class="row">
   <label for="Address">Address</label>
   <div class="col-md-6 ">
      <div class="input-group pull-right">
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         @Html.TextBoxFor(m => m.HomeMainModel.Address, new { @class = "form-control", type = "text", id = "inputFormVal",autofocus = "autofocus", placeholder = "Street Address", required = "required" })
         <div class="input-group-append">
            <div class="input-group-text">
            </div>
         </div>
      </div>
   </div>
   <div class="col-md-6">
      <label id="labelMessageBx" class="text-danger" style="display:none"></label>
   </div>
</div>
...
// function for validating city, street address, street_address_line2, and state_province fields when leaving.
$(function() {
  $('#inputFormVal').blur(function() {
    var city = document.getElementById("inputFormVal").value;
    var expr = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!expr.test(city)) {
      document.getElementById("labelMessageBx").style.display = "inline";
    } else {
      document.getElementById("labelMessageBx").style.display = "none";
    }
  });
});

Answer №1

Insert the following code snippet at the bottom of your page to verify if you have the validator scripts included.

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

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

Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt ...

Examining current elements in database using Node.js and MySQL

There appears to be a problem with the code inside con.query(query, function (err, result, fields). The issue is that it is never being called. This part of the code is meant to verify that when a user signs up, the email they enter is not already in use. ...

I'm searching for a .net web browser engine that can return response cookies along with their designated paths. Can anyone recommend one?

Searching for a web browser engine to use in my C# application (similar to 'WebBrowser' of .Net). I require an engine that can provide a cookie collection per request, with all details such as path and domain included. Despite exploring various b ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

StealJS Module Repathing Techniques

There seems to be an issue with my setup, so I welcome all inquiries. I am utilizing an npm package called xrm-mock for a MS CRM mocking framework. Here is how I have configured it: steal.config({ meta: { "dependencyModule": { deps ...

What is the reason for jsHint's caution: '(var) is declared but not utilized'?

Currently, I am utilizing CodeKit to execute jsHint on my scripts and condense them. I am encountering an error that I would like some clarification on: // create a next button for each text input and wire it for nextQ()! var next = $('<a ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

I am facing an issue with my JavaScript JSON code in an HTML page where the RESTful API array objects are not rendering, even though I am successfully retrieving data from the API. What steps

view image description hereMy issue arises from the fact that the items in the API are not appearing in HTML, where did I make a mistake? <button onclick = "showCountries()">Display Countries</button> <div id = &qu ...

Why is the popover component experiencing issues despite the popover directives functioning properly?

Trying to incorporate BootstrapVue's popovers has been a challenge. I believe I have imported all necessary components. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha3 ...

React Component rendering twice, initial props are appearing as 'undefined' on first render

My React child component (FinalReport.js) seems to be rendering twice. However, on the first render, one of the props is mysteriously undefined, causing an error. I could handle this error, but it doesn't seem like the best approach. The Parent Compo ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

Error: The element 'MvcBuildViews' is not valid for the namespace in nopCommerce version 2.65

After downloading the most recent version of nopCommerce with MVC/Razor, I encountered an issue when attempting to open the project. An error message stating 'invalid child element 'MvcBuildViews' in namespace' appeared. I attempted to ...

What is the best method for incorporating a map legend into a React Leaflet map without relying on refs or making direct changes to the DOM?

I am currently integrating react-leaflet into my project and I need to include a map legend. Currently, I have been achieving this by passing the map's ref to a custom component and rendering null while using a function to generate the HTML for the l ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Issue with reCAPTCHA callback in Firebase Phone Authentication not functioning as expected

I have been working on integrating phone authentication into my NextJS website. I added the reCAPTCHA code within my useEffect, but for some reason, it does not get triggered when the button with the specified id is clicked. Surprisingly, there are no erro ...

Refresh various perspectives

I am facing a challenge in updating views on multiple components simultaneously. To address this issue, I have implemented the use of broadcast functionality. However, when I execute my code without including $apply(), the views fail to update properly. On ...

Javascript floating navigation toolbar

How can I create a minimalist launch bar with a search button that only appears on a page when a specific hotkey is pressed? I want to avoid using large libraries like mootools or FancyBox for this Chrome Extension project to keep it lightweight. Do you ...

Developing a custom Windows hook for capturing menu click events

Is it possible to connect to an external application (such as Microsoft Excel) and detect when a specific menu item is selected (or a ribbon command in more recent versions)? I had considered using the RegisterWindowMessage function in user32.dll, but I a ...

Steps to implement a fixed toolbar in Chrome while ensuring optimal functionality for all other fixed elements

Currently in the process of developing a Chrome extension, I'm interested in implementing a 60px height toolbar that remains visible at the top of all pages. I've researched various tutorials and articles on using CSS translateX, but encountered ...