Dynamically validate AngularJS forms with JSON Schema

I am currently trying to dynamically validate JSON in AngularJS. Unfortunately, I have encountered an issue with loading fields from the schema onto the page. My understanding of AngularJS is limited as I am still new to it. Although I have managed to create the form, I am struggling to implement dynamic validation.

    
        myApp.controller('appController', ['$scope','$http', function($scope, $http) {
            var NUMBER_REGEXP = /^[0-9]+$/;

            $http({ method: 'GET', url: 'JsonSchema.json' })
                .then(function successCallback(response) {
                    $scope.data = angular.fromJson(response);
                    $scope.data = $scope.data.data;
                    console.log($scope.data);
                });

            $scope.greeting = 'success!';

            $scope.handleErrors = function (data) {
                if(data !== undefined && data !== null) {
                    angular.forEach(data, function(value, key) {
                        var form = value.form.field;
                        var fields = value.fields.field;
                        var error = form.errors;

                        if(form.compulsory) {
                            $scope.pageError = form.errors.compulsory;
                        }
                        else if(!(NUMBER_REGEXP.test(filds.field))) {
                            $scope.pageError = error.regex;
                        }
                        else {
                            $scope.pageError = "An unexpected error has occurred, please try again later!";
                        }
                    });
                }
            }
        }]);
    

Answer №1

When facing this kind of issue, utilizing a plunker can often provide assistance. However, the effectiveness of resolving the problem ultimately hinges on the specific library you are employing for JSON Schema validation.

Personally, I am familiar with AngularJS Schema Form. In this case, after loading the JSON Schema, the next step involves setting it on the scope and assigning it to the form in order to facilitate schema provision. This will subsequently enable form validation automatically or require user input before proceeding with validation.

Multiple libraries exist that offer data validation capabilities independently from the form. Currently, one of the most popular choices for pure validation is ajv, while another promising option is djv.

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

Focus on the iPad3 model specifically, excluding the iPad4

I am looking to apply specific CSS that works on iPad 3, but not on iPad 4, or vice versa. Currently, I am able to target both versions by using the following code: @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( m ...

Exploring the concept of creating controllers through ui-router

Currently, I am in the process of developing a web application using AngularJS with ES6. As I am still at the initial stage of learning AngularJS, I have encountered some questions that I couldn't find clear answers to on the internet. 1) In my proje ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

Shuffling Numbers in an Array After Removing an Element with AngularJS

I am working with a JSON array that contains tasks: tasks = [{taskcode:1, taskName:'abc'}, {taskcode:2, taskName:'abc1'}, {taskcode:3, taskName:'abc2'}, ..... ]; If I delete a task with the nam ...

Uncovering the unique properties of custom Items in MUI v5 - RichTreeView: A Step-by-Step Guide

Can custom item properties received asynchronously with MUI - RichTreeView be exposed inside a custom treeItem? For instance, how can the customProperty1 and customProperty2 be accessed within the CustomTreeItem? The console.log to props only shows defaul ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Obtain the computed style by utilizing setTimeout for effective functionality

I want to retrieve the calculated style (background-color) of a span element. Here's my HTML code, consisting of two label elements, each containing an input and a span: <label> <input type="radio" name="numbers" value="01" checked/> ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

Show a success message, clear the post data, and redirect back to the current page

I have a single web page with a contact form. When the form is submitted, I want it to redirect to the same page and display a success message that fades out after a few seconds. Additionally, I want the post data of the form to be cleared. The form also i ...

Modify the font style of the jQuery autocomplete box to customize the text appearance

Hello, I'm a beginner with jquery and currently experimenting with the autocomplete feature. I managed to change the font of the dropdown list successfully but struggling to do the same for the input field itself. Does anyone know how to achieve this ...

Implementing three identical dropdown menus using jQuery and HTML on a single webpage

It seems like I've tangled myself up in a web of confusion. I'm trying to have three identical dropdowns on a single page, each displaying clocks from different cities (so users can view multiple clocks simultaneously). However, whenever I update ...

What's the source of this undefined error and is there a way to eliminate it from the code?

After successfully filtering and reducing the data, I encountered an issue with undefined. I am trying to figure out what is causing this and how I can either remove it or make it visible on the screen without being invisible. You can also check the codes ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Query to retrieve the most recent message from all users and a specific user resulting in an empty array

My goal is to retrieve all messages exchanged between User A and any other user. This is my schema structure: const MostRecentMessageSchema = new Schema({ to: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, from: { type: mongoose ...

Strip the pound symbol from the end of a URL during an AJAX request

When I click on the News tab in my Rails application (version 2.3.4 and Ruby 1.8.7), an Ajax call is triggered to load data. <a href="News" onclick="load_feed();"><u>Show More...</u></a> <script> function load_feed() { $.a ...

Bootstrap 4 tabs function perfectly in pairs, but encounter issues when there are three of them

Having trouble with bootstrap4 tabs not working properly? They function well with 2 tabs using the code below: <div class="row"> <div class="col-12"> <ul class="nav nav-tabs" id="registration-picker-acc-select" role="tablist"> ...

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

Tips for utilizing a variable from a function in one file within a function in another file

Having trouble using the variable counter from one function in a different file? In the first function, I defined counter without using "var" thinking it would make it a global variable. But for some reason, it doesn't seem to work. Help needed! //fun ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...

"I'm curious about how to reset a form in reactjs hooks after it has been submitted

Just dipped my toes into the world of hooks and I'm stumped on how to clear input fields post-submit. Tried form.reset() but it's not doing the trick. import { useForm } from "react-hook-form"; import.... export default function AddUse ...