What is the process for marking a form field as invalid?

Is it possible to validate the length of a field after removing its mask using text-mask from here? The problem is that the property "minLength" doesn't work with the mask. How can I mark this form field as invalid if it fails my custom validation method?

checkDigitsCPF() {
  const numDigits = _.replace(this.advogado.cpf, /\D/g, '').length;
  this.isCPFInvalid = !_.isEqual(numDigits, 11);
}
<div class="form-group">
  <label class="form-control-label" for="field_cpf">CPF</label>
  <input type="text" class="form-control" name="cpf" id="field_cpf" [(ngModel)]="advogado.cpf" required [textMask]="{mask: cpfMask}" (ngModelChange)="checkDigitsCPF()" minlength="11" />
  <div [hidden]="!(editForm.controls.cpf?.dirty && editForm.controls.cpf?.invalid)">
    <small class="form-text text-danger" [hidden]="!editForm.controls.cpf?.errors?.required" jhiTranslate="entity.validation.required">
      This field is required.
    </small>
    <small class="form-text text-danger" [hidden]="!isCPFInvalid">
      This field must have at least 11 characters.
    </small>
  </div>
</div>

Answer №1

When it comes to the element, the validation method should be structured as follows:

// this method will be activated whenever there is a change in value or when the form is submitted

validateField(inputForm): void {
    if (errorCondition) {
        inputForm.controls.fieldName.setErrors({'customLengthError': true})
    } else {
        inputForm.controls.fieldName.updateValueAndValidity()
    }
}

Within the html form, you can display the error message like so:

<small *ngIf="fieldName?.errors?.customLengthError">
    The specific error message.
</small>

Answer №2

Success! I managed to find the solution by developing a personalized directive.

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

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Displaying data in a table using PHP echo after submitting a form

I am struggling to include a form button in my PHP echo statement to update the "status" field of a table row. Despite my efforts, I can't seem to make it work. This is the code snippet with my echo statement: while($row = mysql_fetch_array( $result ...

What is the best way to retrieve the value of this object?

In my project, I am utilizing Angular 8 to extract data from a radio input. However, when I transmit this data to Node.js and then to a MongoDB database, it is not being properly registered. The entry in the database collection appears as follows: "__v" : ...

What is the best way to extract the content within a nested <p> element from an external HTML document using the HTML Agility Pack?

I'm currently working on retrieving text from an external website that is nested within a paragraph tag. The enclosing div element has been assigned a class value. Take a look at the HTML snippet: <div class="discription"><p>this is the ...

What is the best way to activate a component within Angular 2 that triggers the display of another component through method invocation?

I have created a popup component that can be shown and hidden by calling specific methods that manipulate the back and front variables associated with the class. hide() { this.back = this.back.replace(/[ ]?shown/, ""); this.front = this.front.replace( ...

Trouble with embedding video in the background using Next.js and Tailwind CSS

This is the code snippet for app/page.tsx: export default function Home() { return ( <> <main className='min-h-screen'> <video muted loop autoPlay className="fixed -top ...

What is the best way to conceal a specific list item in an Angular 2 template?

I need help figuring out how to hide a selected list item that has been added to another list. I want the added item to be hidden from view in the original list. <div class="countries-list"> <span class="countries-list__header">{{'G ...

Develop a personalized Angular module utilizing ngx-translate functionality

I recently developed my own personal Angular library filled with various components to streamline my projects. I followed a helpful tutorial to create the library successfully. Testing it in another project went smoothly. Now, the challenge is incorporati ...

Issue with menu height persisting while resizing screen

For my responsive design project, I am implementing a menu that switches to a menu button when the width is less than or equal to 768px. Currently, I am using jQuery to dynamically adjust the height of the menu when the menu button is clicked. The jQuery ...

Tips for preventing page breaks (when printing or saving as a PDF) in lengthy HTML tables

Here is the link to a single HTML file (including style and scripts): FQ.html The problem I'm facing can be seen in this image: I've tried several solutions, the latest of which involves the following CSS... @media print{ @page { size:10 ...

Is there a method to modify the arrangement in which 3 specific HTML elements are displayed (i.e., their hierarchy in relation to one another)?

I have 3 "p" elements and I'm trying to find a way to change the order in which they load on the page using JS or CSS. Below is an example of what I've attempted so far. When you click on the first box labeled "about 1," it opens up and displays ...

Learning to utilize the i18n library with React Vite

The developer console is showing the following message: i18next::translator: missingKey en translation suche suche Here is the file structure of my project: vite.config.ts i18n.js test/ src/ components/InputSearch.tsx routes/ public/ de/translation. ...

The system is unable to locate a supporting entity with the identifier '[object Object]', as it is classified as an 'object'

I'm currently working on an Angular 2 application where I am retrieving data from an API and receiving JSON in the following format. { "makes": null, "models": null, "trims": null, "years": null, "assetTypes": { "2": "Auto ...

What is the easiest way to update the border color of a radio button in Material-UI?

I am looking to customize the appearance of the outer ring on Material UI radio buttons. https://material-ui.com/components/radio-buttons/ Currently, my radio button looks like this: https://i.stack.imgur.com/o67mN.jpg However, I would like it to look ...

What is the best way to play AudioBuffer on an iPhone device?

When retrieving audio data from a stream, I encounter an issue with playing audio on iPhone Safari. The sound does not play unless I allow mediaDevice access for audio. Is there a way to play the audio without having to grant this permission? This is the ...

Troubleshooting the problem of fast rotation and scrolling of text in the middle but slow movement at the end with

Currently, I am utilizing the jquery animate function for animating text while also aiming to rotate the text if a specific degree is passed. In order to achieve this, I have implemented the following code snippet: var leftCss = "-"+$('#mydiv'). ...

Creating a navigation bar in React using react-scroll

Is anyone able to assist me with resolving the issue I am facing similar to what was discussed in React bootstrap navbar collapse not working? The problem is that although everything seems to be functioning properly, the navbar does not collapse when cli ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...