What is the best way to implement form validation and conditional markup using AngularJS?

What is the best way to display error messages using AngularJS and forms?

I attempted to validate my form with the following code but it doesn't seem to work:

<div class="form-group" ng-class="{'has-error': obj.title.$invalid}">
  <label for="name">Name</label>
  <input type="text" class="form-control" id="name" ng-model="obj.title" required>
</div>
<div class="alert alert-danger" ng-show="obj.title.$invalid">
  You are required to enter a name.
</div>

http://plnkr.co/edit/C6eU4pIS8FTfA59SCShh?p=preview

Answer №1

One way to implement this is by enclosing it within a <form>, naming both the form and the input, then accessing its validity through formName.inputName

<form name="form">
    <div class="form-group" ng-class="{'has-error': obj.title.$invalid}">
      <label for="name">Name</label>
      <input type="text" name="title" class="form-control" id="name" ng-model="obj.title" required>
    </div>
    <div class="alert alert-danger" ng-show="form.title.$invalid">
      You are required to enter a name.
    </div>
  </form>

It's important to note that the <form> serves as an instance of FormController in angular, which enables angular validation.

Check out the DEMO 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

When I try to pass a variable as a prop to another .js file, it mysteriously transforms into an undefined value

Upon successful login, my app file sets the isAuthenticated variable to true and redirects to the /admin page. The Firebase API call is functioning as expected, allowing access only with a valid username and password. The issue arises when I try to hide t ...

How can I capture events from within a directive's template using AngularJS?

Within my directive, I have a template that includes an <img> element and I am trying to run a custom method from the directive's scope: <my-directive> <!-- Template for my directive --> <p>...</p> <img on ...

When data is retrieved, the state value in Reactjs useEffect remains unchanged

I've encountered an issue while trying to set up a Protected Route in my application. The route should display only if the user is authenticated through an API call, but for some reason, the state value isn't updating correctly. Any suggestions o ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Contrast between employing element selector for concealment and activation tasks

I can't figure out why $('#mdiv input')[1].hide(); isn't working while $('#mdiv input')[1].click(); works perfectly fine. Firstly, I'm curious to understand why. Secondly, how can I get it to work without knowing the id ...

Tips on retrieving the text content of an HTML element using its tag

Is there a way to retrieve the selected text along with its HTML tags using window.getSelection()? When using window.getSelection(), it only returns plain text such as HELLO. However, I need the text with the HTML tag included, like this <b>Hello< ...

When using setState in the onRowSelection event with React's Material-ui tableRow, the selection cannot be properly controlled

Currently, I am working with a material-ui table https://i.stack.imgur.com/JIzLT.png and my goal is to pass selected rows to a function when the DELETE button is clicked. constructor(props) { super(props); this.state = { selecte ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

"Make updates to the data with the help of a button input

I am working on a form that has two input type buttons. The first button is labeled "edit", and when clicked, it enables the input field. The second button is labeled "save", and when clicked, it disables the input field and should save the new values in a ...

Understanding the concept of scope in Javascript is crucial when working with ajax post requests and functions

Looking to improve my JavaScript skills, I've started working with a restful API that provides me with a JSON string. I'm able to successfully parse the information using the following code snippet: $.ajax({ url: './php/bandwidth.php& ...

Create a TypeScript class object with specified constructor arguments

I've been working on a function that is supposed to execute the init method of a class and then return an instance of that class. However, I'm running into issues with maintaining the constructor and class types. This is what I have tried so far ...

Positioning a dropdown menu on top of a Google Map in React with JavaScript: Best Practices

I've been attempting to place a dropdown menu at a specific location on my Google Map, specifically in the top right (or top left is also acceptable). Below is the current output I am seeing: Here is the expected result: Modifications After trying ...

Add the text received from the Ajax request to an array specifically designed for AmCharts

Hello, I'm new to JavaScript and seeking assistance. My goal is to create a chart with real-time data from my MCU, but I'm unsure about pushing a string into an array. Currently, the Array (chart.dataProvider) in this code remains undefined. var ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...

Add a new div in Javascript and include an HTML icon inside

This Django project includes a JavaScript function that generates a new div to display certain data. for (var i = 0; i < files.length; i++) { var newDiv = document.createElement('div'); newDiv.setAttribute("class" ...

Obtain input from request payload in WCF/ADO.NET Data Service

Why are my parameters getting lost when I try to post to an ADO.NET Data Service? This is what my code looks like: [WebInvoke(Method="POST")] public int MyMethod(int foo, string bar) {...} Here's how I'm making the ajax call using prototype.js ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Passing a variable as a property to a nested child component in Vue.js

I am curious about how to efficiently pass variables to nested components. Within my setup, I have a total of 3 components: Main Secondary Tertiary All of these components share a common variable (referred to as sharedVar). If I want to avoid using Vue ...

How much memory is being used by a loop script?

I have developed a script in both PHP and Javascript that goes through a million iterations, breaking down a string into an array and storing the first element of that array into a new variable. Here is the PHP code: class First { public function Iterate ...

When incorporating conditional statements into your code, make sure to utilize the tags <script> along with

I have some script tags as shown below: <script src="cordova-2.5.0.js"></script> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/jquery.mobile-1.1.1.min.js"></script> <script src="js/jquery.xdomainajax ...