What is the best way to implement validation in an input field using AngularJS?

Could you please guide me on how to implement validation in an input field using AngularJS? I am working on a form that is dynamically generated through JSON. I have already added validation for required fields - if the user submits a blank value, it shows a red border. However, I need additional validations such as:

  1. Users should not enter digits or (123) in their names
  2. Users should not enter invalid values like "test" or "abc". If these values are entered, the form should be marked as invalid.

Is it possible to add custom validations to fields?

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

$scope.isSubmitClicked = false;

$scope.myform =''
  $scope.c ={
  "ABC": {
    "type": "LABEL",
    "editable": false
  },
  "Title": {
    "value": "Ms",
    "type": "FIELD",
    "editable": false,
    "dataType": "",
    "required":false
  },
  "First Name": {
    "value": "",
    "type": "FIELD",
    "editable": true,
    "dataType": "",
     "required":true
  },
  "Middle Name": {
    "value": "",
    "type": "FIELD",
    "editable": true,
    "dataType": "",
    "required":false
  },
   "Last Name": {
    "value": "",
    "type": "FIELD",
    "editable": true,
    "dataType": "",
    "required":true
  }
}

   $scope.submit = function ($event) {
        $scope.isSubmitClicked = true;


    };

Answer №1

To achieve live validation on input fields, you will need to create a custom directive. This directive will apply valid and invalid CSS classes to the input field based on your specified conditions. For example, you can make the border of the input field red when it is invalid.

Assuming you are familiar with styling, let's move on to the next part:

<input  ng-required="true" ng-model="modelName" type="text" abc="modelName">

Your custom directive implementation:

App.directive("abc", function() {
return {
    require: "ngModel",
    scope: {
        abc: "=abc"
    },
    link: function(scope, element, attributes, modelVal) {

        modelVal.$validators.abc= function(val) {
            // Write your logic or condition in this function
            // Return false for invalid and true for valid
            /*
            if(condition)
            {
                return true;
            }
            else{
                return false;
            }
            */
        };

        scope.$watch("abc", function() {
            modelVal.$validate();
        });

    }

};
});

If you want to prevent form submission when any field is invalid, modify your form tag as follows:

<form ng-submit="myForm.$valid && submitFunction()" name="myForm">

Ensure that you assign names to your form elements for proper validation.

Here is the controller code you requested (@joy):

var app = angular.module('plunker', ['angularMoment', 'ui.bootstrap']);

app.controller('MainCtrl', function($scope, moment) {

 $scope.isEditableMode = true;
 $scope.isSubmitClicked = false;

$scope.myform =''
   $scope.c ={
  "ABC": {
"type": "LABEL",
"editable": false
},
"Title": {
"value": "Ms",
"type": "FIELD",
"editable": false,
"dataType":"",
"required":false
},
"First Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
},
"Middle Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":false
},
"Last Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
}
}

   $scope.submit = function ($event) {
    $scope.isSubmitClicked = true;


 };

 });

 app.directive("checkInput", function() {
  return {
 require: "ngModel",

 link: function(scope, element, attributes, modelVal) {

    modelVal.$validators.checkInput= function(val) {
       var numberRegex= /^[0-9]+$/;
       if (val.match(numberRegex))
       {
      return false
       }
       else{
         return true
       }
  
        console.log(val);

    };

    scope.$watch("val", function() {
        modelVal.$validate();
    });

}

};
});

Update your HTML input element like this:

<input type="text" name="{{key}}" class="form-control" ng-model="value.value" ng-required="value.required && isSubmitClicked" check-input>

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

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

angularjs populating an array using values from another array

(Still learning angularjs) I attempted to populate an array by parsing a CSV file, and it seems like I was successful as everything is correctly stored in the $scope.videos array. However, when I tried to split that array during page load using the init( ...

Mastering EmberJS 2.7: The Definitive Guide to Binding the 'disabled' Attribute for Buttons

Here is an official guide explaining how to bind a boolean property to the disabled attribute of an HTML element. However, it references a controller in the process. I have a button that, when clicked, transitions the route (it must be a button and not a ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field. Rather than manually adding multiple event listeners like this: <input type="text" na ...

Execute a PHP script using PHP variables using JavaScript

I am facing an issue with calling a URL with a user id parameter using JavaScript to update an SQL table. Manually, the URL works fine (e.g. domain.com/postback.php?userid=userid) but I'm having trouble getting it to work through JavaScript. I recentl ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

Develop a JavaScript function

Is there a way to define the properties of an object in HTML and then create a function in JavaScript that will return that object? This is the HTML code: <object id="desktop" type="application/x-desktop" width="500" height="200> <param name="cl ...

Modify the background color attributes within the provided array

Pagination functionality: I am looking to modify the background color when a user clicks on any element within an array. Currently, the code below allows me to achieve this effect. However, I would like the previously clicked element and all other elemen ...

Encountering NgRx Select Issues While Trying to Access Nested Properties

I've encountered TypeErrors while using NgRx select functions to access nested properties. In my app.module.ts, I have configured the root store as follows: StoreModule.forRoot({ app: appReducer }), The selectors causing errors are related to some ...

Is there a way to add 100 headings to a webpage without using a loop when the page loads

Just joining this platform, so please be patient with me! The task at hand is to insert 100 h3 headings on page load ("Accusation 1, Accusation 2, Accusation 3,...Accusation 100"). We are restricted to using only 1 loop throughout the lab, which will also ...

Is there a method to incorporate HTML5 <keygen> functionality within MS Internet Explorer?

The HTML5 specification has brought back Netscape's idea of the <keygen> tag, which is used to securely generate a pair of keys. This tag has been widely adopted by browser vendors such as FireFox, Safari, Chrome and Opera. However, there is al ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

Share Your Favorite Emojis with My Messaging Field

Is there a way to add emojis to a text area when the user clicks on them? I have created a button that displays all available emojis in a drop-down, but how can I transfer the selected emoji into the text area once the user clicks on it? home.php : <a ...

Encountering "Cannot GET" error following asynchronous AJAX call in ReactJS react.Component

I'm encountering a problem with my reactjs code. After addressing issues related to asynchronous operations, I now face a blank page with an error message saying "Cannot GET /thenameofthepage." Here is the code snippet following the react.Component: ...

JavaScript tabs that smoothly fade in and out

I'm currently working on implementing tabbed content, but I'm struggling with getting the fade effect to apply to the content itself when clicked, rather than just the tab headers. Check out my demo here $('#tab-wrapper li:first').add ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

"Please note that the function of the enter key to navigate between form fields is

When I use the enter key to move between form fields, it's not working as expected: The cursor doesn't move to another field in the form when I press the enter key. Removing the submit button allows the enter key to work properly. The issue se ...