What steps can you follow to allow Form Control to accept empty fields while rejecting all white space characters?

In my current project, I'm working on validating a field in a reactive form. The tricky part is that the field can be left blank as it's not mandatory, but it shouldn't consist only of white space characters. To tackle this issue, I decided to create a custom validator for this specific scenario:

Custom-validator.ts

export function whiteSpaceValidator(control: AbstractControl): { [key: string]: any } | null {
    const check = control.value.trim();
    return check === '' ? { 'whiteSpaceCheck': { value: control.value } } : null;
}

However, I encountered a problem where the validation gets triggered even when the field is completely empty, which is not the desired behavior.

I'm now exploring alternative solutions to address this issue without resorting to iterating through each character in the string to determine if it's a white space character or not.

Answer №1

To determine if the check is both empty and not equal to its original value, you can ensure that trim has removed all whitespace present. This will help validate whether the input meets the required criteria.

export function validateWhiteSpace(control: AbstractControl): { [key: string]: any } | null {
    const checkInput = control.value.trim();
    return checkInput === '' && checkInput != control.value ? { 'whiteSpaceValidation': { value: control.value } } : null;
}

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

moodle - eliminate the need for grading at the same time

I'm currently setting up a Moodle installation and I'm looking for suggestions on how to prevent simultaneous grading. My goal is to have several evaluators grading students across various courses without any conflicts. If you have any recommend ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

What is the best way to deactivate the second selection option?

<select id="title0"> <option value="0">--- disable</option> <option value="1"> books</option> </select> <button id="save" type="submit">Save</button> <select id="title1"> <option value="0"& ...

Seeking a way to encapsulate radio buttons within <span> elements using jquery?

Currently dealing with a SharePoint website where HTML cannot be altered. My challenge is to determine which radio button is selected, but they are enclosed within spans. When I attempt to identify the selected radio button by using the span's title a ...

Send Components to another component without specific TypeScript typespecified

Struggling with a situation where I am faced with the challenge of working around strongly typed variables. The issue arises with a set of icons as components and an icon wrapper component. The wrapper component requires a themeMode variable to determine ...

Choose a specific date on a Materialize datepicker and set it as the selected date

I am currently developing an application using Materialize that includes two datepickers: $(document).ready(function(){ $('#outDate').datepicker({ format: 'dd-mm-yyyy' }); }); $(document).ready(function(){ $(&apos ...

Executing a mousedown event in Ajax while simultaneously running another JavaScript function using JQuery

One issue I am facing involves a JavaScript method. There is a date slider for months that triggers an AJAX call when the month is changed (mouseup event). Within this AJAX call, there is another JavaScript code ($.blockUI) which seems to interfere with th ...

Encountering errors while attempting to update stored information on a consistent basis

I am encountering a very frustrating error while attempting to remove a warning and update it in my database. Despite following what should be the correct syntax, an error persists. The goal is to decrement the user's warning count by 1 and reset the ...

The ngrx state remains hidden

I am working on abstracting the implementation details of my ngrx state by encapsulating it in a shared service class, in order to keep my components clean and organized. Here is an example service class that is registered in my app.module.ts providers @ ...

Do not attempt to use the ID of a created element

Here's the issue I'm facing: I have created an element using the following code: var crt = document.createElement("BUTTON"); var lst = document.createTextNode("\u2103"); crt.appendChild(lst); crt.id = "change"; $(".information").append(crt ...

Rendering deeply nested data in a Vue table

I am currently in the process of updating some older code, transitioning to Vue as a replacement. Everything has been going smoothly except for one specific table that is templated using handlebars. With handlebars and nested {{each}} loops, I can easily ...

What is the functionality of JavaScript RGB color pickers that do not use HTML5?

After inquiring about how HSV color pickers work, I am now curious about the inner workings of RGB color pickers using JavaScript. Specifically, those that do not utilize the HTML5 Canvas API. Could someone provide insight into the concept behind these typ ...

A program designed to automatically upload images

I'm currently working on a website project that showcases various events. Here is a sneak peek: https://i.sstatic.net/W3a4U.jpg While I can customize the HTML and CSS to add more events similar to the one shown above, it becomes tedious having to ma ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Managing large files in Angular 4 and Spring Boot:

I'm currently working on an application that requires the storage of large files (up to a few GB) from clients onto a server. The issue I'm facing is that the server has a maximum heap size of 2 GB, leading to frequent "OutOfMemoryError" occurren ...

Modifying an item within an array will not automatically result in an update to the corresponding HTML elements

When editing the object, it is done in JSON format, but only the previous data appears in the browser. To retrieve a list of products from local storage, I utilize these hooks: const Cart = () => { const [products, setProducts] = useState([]); c ...

After clearing the option, the onChange function stops functioning

I'm facing an issue with the following code: success: function (data) { $('#' + idDivRefresh).endLoading(); if (data.message != '@Geral.Sucesso') { $('#' + idDropDown + ...

Is there a way to incorporate an 'input' type within an Icon Button component from Material UI in a React project?

Kindly review my code below. I have revamped it for clarity so you won't need to stress about important details! const test = () => { return ( <label > <input type='file' multiple style={{ display: &ap ...

Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript? Here is some sample code: type KeyUrl<T> = T extends `/${infer U}` ? U : never; type TUrl<T> = { [k in KeyUrl<T>]: string }; // ---------------------------------- ...