Ensuring the accuracy of user input in an AngularJS form

Attempting to validate user input in a form before sending it to the server, however, encountering an issue where the input field is not being checked and no error is being reported. Implemented a custom validator directive:

`var QUERY_REGEXP = /[A-Z,a-z,0-9]{1,20}/;
 app.directive('q', function() {
 return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
  ctrl.$validators.q = function(modelValue, viewValue) {
    if (ctrl.$isEmpty(modelValue)) {

      return true;
    }

    if (QUERY_REGEXP.test(viewValue)) {

      return true;
    }

    return false;
  };
  }
 };
});` 

Corresponding HTML code:

<div ng-controller="CreditsController">     
<div style="padding-top:20px" >
<form name='form' novalidate>
<b>Enter Name:&nbsp;&nbsp;</b><input id="creditq" ng-model='query1' name='query1' type="text" q />
<button id="Submit" ng-click='click()' ng-value='search' required>Search</button><br/><br/>
<span ng-show="form.query1.$error.query1">The value is not valid!</span>
</form>
</div>

Struggling to identify the issue or where mistakes may be occurring. Any assistance would be greatly appreciated.

Answer №1

There are a few issues that need to be addressed:

  • The regular expression /[A-Z,a-z,0-9]{1,20}/ will match any string containing upper and lower case letters, numbers, and a comma. However, the {1,20} quantifier may not work as intended because it does not specify that the pattern must encompass the entire string. It is recommended to use /^[A-Za-z0-9]{1,20}$/ instead.

  • According to this resource, the test() method called multiple times on the same global regular expression instance will move past the previous match. To address this issue, you can either recreate the regex on each validation call or reset the lastIndex property to 0.

  • Since your validator is named q,

    <span ng-show="form.query1.$error.query1">The value is not valid!</span>

    will never display the error message because the $error object does not have a query1 property. Make sure to reference the correct validator name, which in this case is q.

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

Trouble with Angular localization module displaying codes instead of non-ASCII characters

I am currently utilizing a module from this source to facilitate localization efforts. However, I have encountered an issue where special characters are being displayed as their corresponding ASCII codes instead of their actual symbols. For example, &a ...

Verify whether the user's email is registered in the database

I have a login form and I want to verify if a user's email exists in the database, but I'm not sure about the syntax for integrating Angular with Node. In my Main.js file, I have an ng-click on the submit button that triggers this function. I ex ...

Is there a way to convert a regular controller into a service or factory in AngularJS?

Hello there! I am currently working on a web application and I am looking to pass my array to my controllers. Your assistance is greatly appreciated! MyControllers.controller('MyCtrl',['$scope', function ($scope){ $scope.items = [ ...

I'm having trouble with my dropdown navigation menus - they keep popping back up and I can't seem to access

My website is currently in development and can be accessed at: The top navigation bar on the homepage functions properly across all browsers. However, there are three sections with dropdown submenus - About Us, Training, and Careers. These dropdown submen ...

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

Exploring ways to incorporate or eliminate animations on mobile devices using html/css

Is it possible to control animations on different devices using media queries? For example, can you show an animation only on mobile devices while hiding it on desktop or laptop? Conversely, is there a way to add an animation specifically for mobile device ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

Extension for Chrome that switches between active and inactive modes

I have been attempting to create an extension that can toggle the functionality of another specific extension on and off. Despite numerous attempts, I have not been able to find a solution that works effectively. Essentially, my extension displays a popup ...

Sharing cacheFactory data between multiple blocks in Angular.js is a great way to improve

Is there a way to share the same instance of $cacheFactory between my .run block and a service? In my .run block, I have defined a $cacheFactory like this: var cache = $cacheFactory('cacheName'); I have added some data to this cache: cache.put ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Oops! There seems to be an error in my code - it's expecting a semicolon. I'm currently working on developing an authentication system using credentials with next auth

#pages/api/auth I'm currently in the process of developing an authentication system using Nextauth in Next Js. I encountered an issue with authenticating using credentials while following a tutorial on YouTube.I've double-checked the syntax multi ...

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

Hash Symbol refuses to function in IFRAME

The Request.QueryString contains the file path example Temp\file#hashName.jpg protected void Page_Load(object sender, EventArgs e) { string filePath = Request.QueryString["fileName"]; iframes.Attributes.Add("src", filePath); } It then goes to the Ma ...

What is the best way to display information in a Handlebars template file?

Having trouble displaying data in the template using NestJS with mysql. Here is the code snippet from controller.ts: import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common'; import { P ...

The Div element refuses to budge from its current position on the page's layout

$("#pg2_main_display_div ").css({ top: -$("#pg2_main_display_div").offset().top }); The value generated by -$("#pg2_main_display_div").offset().top is currently -1033. Unfortunately, this code does not seem to be functioning properly as the content ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

The rendering of React child components is not functioning

Hi there! I am new to using React and I am currently facing an issue with rendering components. My problem is that only the parent component is being displayed, and the child components are not being recognized by React. Here is the snippet of code from m ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...

Tips for implementing $routeProvider's resolve function in electron-angular-boilerplate

I am encountering an issue with loading JSON data before entering the main controller in my project. Using this project as a template, I made alterations to only dist/app/home/home.js where the changes were implemented: angular.module('WellJournal&a ...

Dynamic resizing of DIVS occurs when the address bar is hidden on Mobile Chrome

As I work on designing a website, I have utilized sections with the same class and set their height to 100vh. Everything appears to be functioning correctly when viewed on a browser, however, issues arise when accessing the site on phones. Whenever I scro ...