Locate the unique symbol within an array

I am facing a challenge with validating user input in an input box where alphanumeric values are allowed along with certain special characters. I need to display an error message if the user enters a special character that is not supported by my application.

   var inputKey = "abcdfg34$@!"

My approach involves filtering out the special characters from the string first.

   var inp = inputKey.replace(/[a-zA-Z0-9]/g, ''); // Now ip = @!

$scope.specialchar contains a list of allowed special characters

   $scope.specialchar = [@,#,$,%,<,^,<];

   for(var i in $rootScope.specialChar ){

              if(( inp.indexOf($scope.specialChar[i].value) > -1 ))
                  {
                  $scope.charAllowedText = true;
                  count++;
                  }

          }
         if(count == 0) - display error messagae

The current code seems to be effective in detecting the occurrence of the first unsupported special character. In the given example, the character (!) is not on the approved list. However, when my string contains @! both conditions (count == 0) might fail as only one character is checked. I also aim to include which specific unknown special character was entered by the user in the error message.

I would appreciate any insights into what could be going wrong and how I can address this issue.

Answer №1

Filtering Disallowed Characters with Regular Expressions

var allowed=['-','@'];
var regex=new RegExp('[a-z0-9'+allowed.join('')+']','ig');

var tests=[
  "holi-java",
  "@name",
  "@-#$@"
];


tests.forEach(function(test){
  console.log(JSON.stringify(test)+" contains disallowed characters:"+JSON.stringify(test.replace(regex,'')));
});

Using JavaScript to Filter Disallowed Characters

    var allowed=['-','@'];


    var tests=[
      "holi-java",
      "@name",
      "@-#$@"
    ];
    function findDisallowed(input){
       var rest=input.replace(/[a-z0-9]/g,'');
       var disallowed=[]; 
       for(var i in rest){
         if(allowed.indexOf(rest[i])==-1)
          disallowed.push(rest[i]);
       }
       return disallowed;
    }

    tests.forEach(function(test){
      console.log(JSON.stringify(test)+" disallowed characters found:"+JSON.stringify(findDisallowed(test)));
    });

Answer №2

To start off, it is important to wrap each character in the array with quotes when setting $scope.specialChar to ensure that they are read as strings:

$scope.specialchar = ['@', '#', '$', '%', '<', '^', '<'];

Furthermore, when checking if the input contains any of the special characters, simply use $scope.specialChar[i] without adding .value, as you are aiming to access a specific element in an array, not its value property.

inp.indexOf($scope.specialChar[i]) > -1)

Answer №3

Here is a more efficient directive to replace the code above:

angular.module('test')
  .directive('validChar', function() {
    return {
      require: '?ngModel',
      link: function(scope, element, attrs, ngModelCtrl) {
        if(!ngModelCtrl) {
          return;
        }

        ngModelCtrl.$parsers.push(function(val) {
          if (angular.isUndefined(val)) {
            val = '';
          }
          var clean = val.replace( /[a-zA-Z0-9]/g, '');
          if (val !== clean) {
            ngModelCtrl.$setViewValue(clean);
            ngModelCtrl.$render();
          }
          return clean;
        });

        element.bind('keypress', function(event) {
          if(event.keyCode === 32) {
            event.preventDefault();
          }
        });
      }
    };
  });

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

Can an image map be utilized within an <a> element?

I am attempting to implement an image map within an <a> tag. It seems to be functioning correctly in Chrome, but I am encountering issues with it not working in Internet Explorer. Is it acceptable to use an image map in an <a> tag? Below is th ...

The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here. Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars. Here i ...

Version 2.0.0 of ui-bootstrap causes popovers to malfunction when triggering expressions are used

Before, in ui-bootstrap 1.3.3, I successfully used a popover trigger on a button with the following configuration: popover-trigger="click outsideClick" This trigger allowed me to open the popover when clicking the button and close it when clicking anywher ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

Spin and flip user-submitted images with the power of HTML5 canvas!

I am currently working on a profile upload system where we are implementing image rotation using the HTML5 canvas object with JavaScript. Although the uploaded image is rotating, we are facing issues where parts of the image are being cut off randomly. So ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

Steps to make a unique custom tooltip without using jQuery by utilizing the title attribute

I am looking to implement a tooltip similar to the one shown in the image. The value in the title tag is dynamic and fetched from the controller. https://i.sstatic.net/C2v3D.png Below is the code snippet of my table: <table border="1" cellpadding="10" ...

Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input. I attempted to use userEvent.type(inputEl, '1') an ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: https://i.sstatic.net/Y10X7.png The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').Data ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

What is the method for populating a dropdown using ajax in the Jade template engine?

Looking to dynamically populate a dropdown based on the selection of another dropdown. Here's the code snippet: script. var b_name = []; function jsFunction() { var client = document.getElementById('drop_client'); var c_name = cli ...

How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3'); let letters = new Array('a','b','c'); let length = numbers.length; let str = 'abcdefgabcdefg'; for (let i=0; i<length; i++) { let regex = new ...

The JavaScript Autocomplete feature fails to clear suggestions when there is no user input detected

After watching a tutorial on using Javascript with Autocomplete and a JSON file, I implemented the code successfully. However, I encountered an issue: When I clear the input field, all results from the file are displayed. I've tried adding code to cl ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

Is it preferred to utilize v-show in combination with v-for?

I understand that using "v-if" with "v-for" is discouraged, but I'm unsure about the case of "v-show" since it simply toggles the display attribute. Here is the code for reference. Essentially, I am trying to switch between 3 different types of fi ...

Require the field if the country selected is the United States

I am working on implementing form validation for the STATES dropdown, but I want it to only be required if the selected country is USA or CANADA. Currently, my validation works regardless of the country selection. It forces the user to select a state even ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

The list item click event is not triggered when new list items are added

I've run into a bit of confusion with my code. Everything seems to be working perfectly fine until I introduce new items. Take a look at a sample of my items However, once I make changes to my list, the click function stops working. Check out a sa ...