In AngularJS, one way to mark an input field as ng-invalid is by following these steps

I need to validate an input field for credit card numbers.

The input should only be considered valid once it reaches a minimum length of 13 characters. To allow users to enter spaces in the field, I have implemented a JavaScript function to remove these spaces. Within this function, I want to validate the credit card number (sans spaces) and mark it as ng-invalid if the length is less than 13 or greater than 16.

Here's the basic idea:

$scope.ccHandler = function() {
   if ($scope.ccNumber == '') {
      document.getElementById("ccProvider").disabled = false;
   }
   $scope.ccNumber = inputCC.value.split(' ').join(''); 
   console.log("This is my CC: " + $scope.ccNumber);
   isValidCreditCardNumber($scope.ccNumber);
   getCreditCardProvider($scope.ccNumber);
   document.getElementById("ccProvider").disabled = true;
   if ($scope.ccNumber.length < creditCardNumberMinLength || $scope.ccNumber.length > creditCardNumberMaxLength) {     
      console.log("ccNumber is still invalid!");
   }
}

This code snippet would fit into the XHTML like so:

<div class="form-group" ng-switch-when="CreditCard">
   <label class="col-xs-3 col-sm-3 control-label">Credit Card Number</label> 
   <div class="col-xs-5 col-sm-5 col-md-5">
      <input name="ccNumber" class="form-control" type="text" id="inputCC" ng-change="ccHandler();updateCount()" ng-model="ccNumber" ng-required="true"/>
   </div>
</div>

How can I implement this effectively?

Answer №1

To achieve this functionality, utilize the $setValidity method. It is crucial to assign a name attribute to the <form> element in order for it to function properly.

<form name="myForm">
   <input name="ccNumber" ng-model="ccNumber">
   <span ng-show="myForm.ccNumber.$error.minLength">
      A minimum of 10 characters are required for a valid cc number
   </span>
</form>

Next, you can manually set the validity like so:

$scope.myForm.ccNumber.$setValidity("minLength",$scope.ccNumber.length>=10);

For a demonstration, refer to this working plnkr: http://plnkr.co/edit/7J326LR194SaoE2TmHuU?p=preview

Answer №2

This is the solution that solved my issue:

$scope.formName.creditCard.$setValidity("creditCard", true);

Answer №3

To limit the character length of your input field, simply utilize the ng-maxlength and ng-minlength attributes.

For a practical demonstration, refer to the example provided in the AngularJS documentation.

<input type="text" name="username" ng-model="user.name" 
     ng-minlength="6" ng-maxlength="20">

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

Utilizing Jquery Ajax to send a post request containing input values through Tampermonkey

I encountered an issue with my code - even though the logs in console show that it is working, I am unable to send the values to my server using AJAX post. jQ(document).on("keyup", "form input", function () { var value = jQ(this).val(); ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

In Rails 3, you can utilize JavaScript to submit a form_tag remotely, however ensure that it submits as

I am trying to implement a form_tag in rails 3 that can be submitted using ajax instead of html through javascript. Despite setting the form to submit as javascript, it still submits as html when clicking the submit button. - form_tag({:controller => " ...

Error: Unable to access the 'wsname' property of an undefined value

I am attempting to retrieve values from a database using the code below (login.js) $.post("http://awebsite.com/app/login.php",{ rep1: rep, password1:password}, function(data) { if(data=='Invalid rep.......') { $('input[type="text"]').c ...

Is the list being updated but the data not reflecting on the DOM in a ReactJS application?

My coding solution for creating a TODO list has a glitch - when I add an item, the list updates as expected, but when I try to delete an item, the list does not refresh. import React, { useEffect, useState } from 'react'; import './App.css&a ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

Is there a way to determine the names of the functions that are being called?

I'm working on mastering Google Development Tools. Is there a way to determine which specific functions, especially those in Javascript, are needed before a page can load successfully? ...

What is the process for generating a subpage within the main page without the need to navigate away from the primary

On my main page, I have a login button. Instead of redirecting the user to a new page, I want it to simply display a login box. You can see an example of this on medium.com when you click on 'sign in'. Is it possible to achieve this with only HTM ...

Difficulty validating RSA signature on the server end originating from client-side Javascript

Utilizing the forge library on the client side for creating signatures looks like this: //Client Side var md = forge.md.sha256.create(); md.update(encryptedVote, 'utf8'); var pss = forge.pss.create({ md: forge ...

Steps to Make Your Node.js Server Always Accessible to External Applications

I have been searching for a solution to this issue everywhere, but I seem to be unable to find a clear answer on how to execute this task. Recently, I created a basic server using node.js that retrieves two numbers from a website API and displays them on ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...

What strategies do you use to handle conflicts that arise when components within dependencies share identical names?

This question delves into the realm of Angular architecture and the intricacies of working with it. I have developed a basic Angular application which includes a main module named App. Within App, there are two dependencies, Dep1 and Dep2, both of which c ...

Error connecting to the server at localhost on port 27017: Connection attempt unsuccessful

I'm having an issue that I can't seem to resolve, and I suspect it might be related to my connection string. Some of my classmates faced the same problem, but their connection string doesn't work for me. Any ideas on how to tackle this? SER ...

Add elements from one array into designated positions within another array

Is there a way to extract the days and months from the current week and store it in an array within a specific field of an object? I need to be able to later iterate through this array to display the data. I am unsure on how to achieve this. <div v-for ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

I'm having trouble getting the 'npm run dev' command to work, what steps should I take next?

When I try to run npm run dev in the command line, I encounter an error that I've been unable to resolve despite trying multiple solutions. Below is the content of my package.json file: { "name": "project", "version": "1.0.0", "description": ...

Is the JSON parsing issue being caused by Bodyparser?

I am encountering an issue with parsing JSON on my server using the body-parser NPM module and Express. The JSON data is not appearing correctly on the server for some reason. Here is a snippet of my server code: ... app.use(bodyParser.json()); app.use(bo ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

javascript - Alternate text colors several times within specified color ranges

Seeking assistance with changing the text color multiple times from #627CA9 to #FFFFFF and vice versa. Here's what I've tried: function changeColor(id) { var x = document.getElementById(id); if (document.getElementById(id).style.color = " ...