Tips on indicating a mandatory field in AngularJS using a red border

Is there a way to display a red border around required fields in AngularJS forms? I am populating the form from JSON data where a field is marked as "required" : true. These required fields need to be filled out by the user. How can I implement a red border to indicate that these fields are mandatory?

Below is a snippet of my code:

 "First Name": {
    "value": "naveen",
    "type": "FIELD",
    "editable": true,
    "dataType": "",
     "required":true
  },
  "Last Name": {
    "value": "",
    "type": "FIELD",
    "editable": true,
    "dataType": "",
    "required":true
  }

Both First Name and Last Name are marked as required.

/* Add your custom CSS here */

.error {
  corder: 1px solid red;
}

I would like to apply this CSS class to the field on a button click if any of the required fields are left empty.

View the full code example here.

How can I modify the form to show red borders around invalid or incomplete fields?

Answer №1

If you are already utilizing a form element, you will benefit from the features that come with the AngularJS provided form directive. Simply connect the validation accordingly.

To achieve your desired outcome, make the following HTML change:

<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
    <input type="text" name="{{key}}" class="form-control" ng-model="value.value" ng-required="value.required">
</div>

Some key points to note with this suggestion:

  • Assuming you are using Bootstrap 3.3, the framework already includes error state validation styling (e.g. observe the form-group has-error combination). Creating a separate red border CSS class is unnecessary unless preferred. Further details available here.
  • Every input field requiring validation should have a defined name attribute
  • The validation status of each input field can be accessed via the form controller (i.e. myform)

View a modified version of your Plunker with the above recommendations incorporated.

Edit

In response to additional feedback, implement the following changes:

  • Place the submit button below the form element
  • Add novalidate to the form element to disable native browser validation
  • Expand the ng-class condition to include the $touched and $submitted properties

Updated Plunker fork available here.

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

Can uniform columns be created in separate HTML elements?

Looking to create a uniform list in HTML, where the columns inside each panel line up perfectly. See the desired layout: https://i.sstatic.net/FbbPu.png In this example, Col_1 has a width of "BBBBB", as it is the widest content in that column, ...

Discover the best places to master AJAX

Although I have come across some related questions here, none of them exactly match mine. I am aware of excellent resources like code-school and code-academy where you can improve your PHP and JS skills by coding directly on the website. However, I am wo ...

Pass the full path of the Dropzone file to the Rails controller

I'm currently working on extracting the complete file path from a dropped folder in Chrome's Dropzone. All file upload data is being transferred correctly, but I also need to capture the full path of the uploaded file. Despite my efforts, I&apos ...

Navigating the challenges presented by CORS (Cross-Origin Resource Sharing) and CORB (Cross-Origin Read Blocking) when utilizing the FETCH API in Vanilla Javascript

Looking to update text on a website using data from a JSON file on another site? This scenario is unique due to restrictions - can't use JQuery or backend elements like Node/PHP. Wondering if vanilla JavaScript can solve the problem? While some worka ...

The issue of jQuery not functioning properly within a Rails environment

Despite my efforts, I am still struggling to make jquery work in rails. I have installed the 'jquery-rails' gem and added the require statements in the application.js file. Below is a sample test page that I have been testing: <!DOCTYPE htm ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

Accessing the router URL directly is proving to be ineffective

Currently, I am utilizing react-router in my project and everything is functioning perfectly except for when I directly access the URL. Specifically, if I click on a Link within the application that navigates to "/quizreview?quizId=nAUl3DmFlX", it works fl ...

Connecting to a different HTML file functions smoothly on a local server, but encounters difficulties when uploaded to a web server

Here is the structure of my folders: updated /public twitter.html /styles styles.css /views index.html server.js package.json I have an index.html file that is linked to twitter.html. In the .js file, I am using Express and Node.js to link them ...

The scroll function within the inner div is malfunctioning on the Firefox browser

Scrolling within inner div is not functioning properly in the Mozilla Firefox browser. However, it works seamlessly in Chrome. Is there a workaround for enabling scrolling in Firefox? Here is the fiddle link: http://jsfiddle.net/t6jd25x9/2/ body { f ...

Is it possible for me to connect one element to another using CSS or JavaScript?

On my website, there are three columns of interactive elements that can be scrolled vertically. Users are able to select one item from each column, and once selected, the chosen elements are connected by lines. The challenge I am facing is determining ho ...

Learn the process of eliminating special characters from input or textarea fields with AngularJs!

My attempts to integrate an AngularJS directive to remove special characters from input and textarea fields have been unsuccessful. Despite no errors being reported in the console, I am facing issues with the character count tooltip not displaying numbers ...

What is the best way to ensure that circles only touch each other by their edges?

Trying to align three circles touching each other has been a challenge for me. Although I have successfully managed to make two touch, the third one remains elusive. How can I ensure that all three circles are in contact with each other, especially when th ...

Tips for effectively passing query string parameters in Angular

I am looking to make an HTTP request with parameters through a query For instance: URL: https://api/endpoint?d=1&value=2 ...

What is the method for dividing a string into separate parts without the use of del

I have the number "513" in a string format, and I need to convert it into an array consisting of ["5", "1", "3"]. My updated solution using code is: function convertToArray(num){ let numArray = num.split(''); console.log(numArray); } co ...

Oops! There seems to be a mistake - the provider setPageProvider is not recognized

Struggling to implement pagination on my page using the AngularJS framework. Encountering the error Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. Despite rearranging the code, the issue persists. Attempted following a tutorial fr ...

Encountering a blank screen issue post building with vue-cli-service and electron:build

I have attempted various solutions to eliminate the blank screen issue in my electron application: (1) I tried commenting out createProtocol and loadURL('app:...') in background.js and instead using path.join(): if (process.env.WEBPACK_DEV_SERVE ...

The correct method to remove a specific attribute from the primary state in Redux that employs combineReducers - React Redux

I have been working on an app that requires authorization features such as registration, login, and logout. To achieve this, I am using redux. While the registration and login functionalities are operational, I encountered issues when attempting to delete ...

What is the best way to display the unique $index for an array retrieved from Firebase?

I am currently facing an issue. Everything is progressing smoothly. I am using ngRepeat to display lists that are Arrays from Firebase using the $asArray() function. In addition, I am applying a "reverse" filter so that new items appear at the top. Now ...

Retrieve JSON data generated within a JavaScript-powered webpage

My issue involves two HTML pages: 1) The first HTML Page (page1.html): <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <script type="text/ ...

Is it possible to inject JavaScript into the DOM after it has been loaded using an AJAX call?

I have a specific div element identified by the id #id1 that contains clickable links. Upon clicking on these links, an AJAX call is made to retrieve additional links from the server. My current approach involves replacing the existing links within #id1 w ...