Custom AngularJS directive that permits only alphabetic characters, including uppercase letters and the ability to input spaces

I'm currently working on an AngularJS directive that is meant to only allow alphabetical characters, however, I've encountered an issue where it disables caps lock and space functionality. While the main goal is to prevent special characters and numbers as input, I still want to enable caps lock, space, and shift keys since users may need to input their names in capital letters. Any suggestions on how to achieve this? I have opted for a directive instead of using the ng-pattern library.

app.directive('validEn', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl, SweetAlert) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                var clean = val.replace(/[^a-z]+/g, '');
                console.log("sfdsfd")
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

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

Answer №1

To modify your regex, switch from using

var clean = val.replace(/[^a-z]+/g, '');
to
var clean = val.replace(/[^a-z|^A-z|^\s]+/g, '');

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

Is there a way to set the default state of a checkbox in a spring-form?

I have set up my web content using spring-boot with .jsp files. The controller code is as follows: @Slf4j @Controller @AllArgsConstructor @SessionAttributes({"language", "amount", "words"}) public class LanguageController { private LanguageService lang ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

`store and utilize the data retrieved from chrome.sync.storage.get()`

As I work on a Chrome extension, I am facing an issue with retrieving information from chrome.storage. This involves saving some data in the options page and then accessing it in the content_script. In the options.js, this is how the information is saved: ...

Some places may not have detailed information available when using the Google Places API

Greetings I am currently in the process of developing a page on my website that utilizes the Google Places API along with the user's geographical coordinates (latitude, longitude) to locate nearby restaurants. In my code, I have implemented a functio ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

JavaScript-powered dynamic dropdown form

I need help creating a dynamic drop-down form using JavaScript. The idea is to allow users to select the type of question they want to ask and then provide the necessary information based on their selection. For example, if they choose "Multiple Choice", t ...

What is the method for adding a default endpoint to Angular $http requests?

In my Angular application, I have a process where variables are retrieved from an environment file and then updated using Grunt. Upon completion of the grunt task, a specific variable is set in environment.js as follows: var envBaseUrl = 'https://live ...

Retrieve the intrinsic height of an element using AngularJS

I'm trying to access the naturalHeight of an image using a directive I created: angular.module("Discavo").directive("imagecrop", function() { return { restrict: "C", link: function(scope, elem, attrs) { console.log(angular.element(ele ...

Navigating the route on express.js using two strings can be done by matching them effectively

I have a single route function that should match two different paths. The goal is to create profile pages for team members on a website, which can be accessed at www.domain.com/name. However, some team members prefer to use nicknames instead of their actua ...

Problem encountered when running "npm install" following the configuration of an AngularJS project using Yeoman

Encountering an issue during or after the creation of an Angular project using the command: yo angular While installing devDependencies from the package.json ("npm install" which is triggered by yo angular), I noticed certain modules were missing in the ...

Is it possible to utilize a designated alias for an imported module when utilizing dot notation for exported names?

In a React application, I encountered an issue with imports and exports. I have a file where I import modules like this: import * as cArrayList from './ClassArrayList' import * as mCalc1 from './moduleCalc1' And then export them like t ...

Dragging an image in KineticJS gets stuck after the drag operation is completed

My experience with KineticJS has been positive so far, but I have encountered an issue with dragging images. In the example below, I have set the image to be draggable, but after the initial drag, it seems like the image can't be moved again. var sta ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

In a Next.js project, Typescript seems to be overlooking errors related to proptype definitions and function types

Greetings everyone! I am currently working on a project using TypeScript and have implemented various rules and elements. However, I am facing issues with type errors for functions and props. Essentially, when using any function, it is necessary to specify ...

Adjusting the initial index for looping in AngularJS

Currently, I am working on a Web application utilizing AngularJS. One issue I am facing is implementing a for loop in the html using AngularJS conventions. Allow me to explain my situation below. In AngularJS, we typically iterate through items using ng-r ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

Tips for chaining actions in Javascript using ActionSequence, LegacyActionSequence, or a similar method

I encountered an error while attempting to execute this example, despite trying both ActionSequence and LegacyActionSequence. I am in search of the correct method to chain actions. My attempts to find a solution in resources such as https://seleniumhq.git ...