Ensuring that the field is empty is acceptable as long as the validators are configured to enforce

I have successfully created a form using control forms.

idAnnuaire: new FormControl('',[Validators.minLength(6),Validators.maxLength(6)]),

However, I am facing an issue where when the field is left empty,

{{form.controls.idAnnuaire.valid }}
is showing as true instead of false (expected behavior).

I prefer not to set the control form as required because users should be able to submit the form even if they haven't filled in the idAnnuaire input, as long as other fields are completed.

Here is a Stackblitz demo for reference.

Answer №1

To address this issue, there are several possible solutions available. However, in the context of this particular situation, I believe creating a custom validator would be the most effective choice. An example implementation could look something like the following:

// Implementation of Custom Validator

// This section is typically uncommented in the full application
// import { FormControl } from '@angular/forms';

// Placeholder values for demonstration - actual input should come from form
const validInput = { value: '123123' };
const invalidLowValue = { value: '123' };
const invalidHighValue = { value: '123123123123' };
const invalidNoValue = { value: '' };

// The following function needs to be exported without 'export' keyword for snippet compatibility 
function validateOptionalFieldWithLength(input){
  return validateField(input, { validField: true });
}

// This section is typically uncommented in the full application
// function validateField(input: FormControl, error: { [errorKey: string]: boolean }) {
function validateField(input, error) {
  let isValidField = true;
  let fieldValue = input.value;

if (fieldValue && fieldValue.length === 6 ) {
    return null;
  }
  return error;
}


console.log('Expecting valid result (null): ' + validateOptionalFieldWithLength(validInput));
console.log('Expecting validation error: ' + validateOptionalFieldWithLength(invalidLowValue));
console.log('Expecting validation error: ' + validateOptionalFieldWithLength(invalidHighValue));
console.log('Expecting validation error: ' + validateOptionalFieldWithLength(invalidNoValue));

// Your Component

// Import your custom validator


idAnnuaire: new FormControl('', 
              Validators.compose([
                validateOptionalFieldWithLength
              ])
            )

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

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...

Could someone please help me identify the mistake in this code? I recently created a new class, imported it into a .ts file, and then proceeded to define

Upon checking the console, an error message appeared stating that Recipe was not defined. To resolve this issue, I made sure to include the necessary class definition in a separate file at the end of my code. The import statement: import { Recipe } from ...

The challenges of type verification in Redux reducer

I'm currently facing two specific challenges with Typescript and the Redux reducer. Reducer: const defaultState = { selectedLocation: { id: 0, name: 'No Location' }, allLocations: [{ id: 0, name: 'No Location' }], sele ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

What causes an array of type `never[] & number[]` to be generated when using `Object.assign`?

Take a look at this code snippet: const arr = [1,2,3] const res1 = arr.slice() const res2 = Object.assign([],arr) When using arr.slice() to create a shallow clone, the resulting array res1 will have a type of number[], just like the original arr. However, ...

Guide on displaying toaster notifications using promises in Angular 2

Hey everyone, I've encountered a problem with promises while handling a 500 internal server error. I have set up Promises to handle post and get services, but when catching the 500 response, I can't seem to display it in a toaster. Here's my ...

Understanding how to extract a specific value key from a JSON object in Typescript while utilizing Angular can greatly

I'm currently facing a challenge in Typescript with Angular where I need to retrieve a specific value from a JSON constant. While I am aware of the performance implications, I am wondering if there is a more efficient way to access this value within t ...

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

tsc is not recognizing the configurations in my tsconfig.json file

Running tsc in my project's directory is causing an error to be outputted (as shown below). This is my first attempt at using TypeScript and Node.js. Please consider me as a complete beginner. Operating system: Ubuntu 15.10 64bits NPM version: 2.4. ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Warning from Google Chrome: Ensure password forms include optional hidden username fields for improved accessibility

Upon visiting the "reset password" route of my single-page application and checking the Chrome browser console, I am presented with a warning message: [DOM] Password forms should contain (optionally hidden) username fields for accessibility: (More info: g ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

Prevent authenticated users in Angular2 from accessing certain routes

In the main.ts file, I have defined a set of routes: const routes: RouterConfig = [ { path: '', component: HomeComponent }, { path: '', redirectTo: 'home', terminal: true }, { path: 'dashboard', component: Das ...

When another page is refreshed, Angular routing redirects back to the home page

Within my application, there is a homepage that appears after the user logs in, along with some other pages. However, I've encountered an issue where when I navigate to one of these other pages and then refresh the page, it redirects me back to the ho ...

Troubleshooting npm installation issues with Angular 2 Quickstart guide (URL: https://angular.io/docs/js/latest/quickstart.html)

I am currently facing issues when trying to set up Angular 2 on my Ubuntu 15.10 system. Despite multiple attempts, the installation fails and I receive error messages. Even after attempting to install Angular 2 using the npm package command sudo npm insta ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...