Proper Validation in Angular6: Preventing Empty Input Fields

I've been working with Angular and grappling with the challenge of validating input fields to prevent white spaces. I decided to experiment with an IF statement, as shown below. Everything seemed to be working smoothly until I encountered an error message when a particular input field was left blank:

ERROR TypeError: formValue.employee.trim is not a function

onSubmit() { //when  the user clicks the submit button
 const formValue = this.telephoneForm.value;
 this.submitted = true;
  if (this.telephoneForm.invalid) {
   const invalidControls = this._findInvalidControls();
    if (invalidControls.length) {
    $("[formControlName=" + invalidControls[0] + "]").focus();
   }
 }

 if (
   this.telephoneForm.invalid ||
   this.alreadyExist ||
   this.noEmployeesFound ||
   this.noDepartmentsFound ||
   this.noVendorsFound
 ) {
   return;
 }


 if (
  (formValue["department"] === null ||
  formValue["department"].trim() === "") ||
  formValue["employee"] === null ||
  formValue["employee"].trim() === "" ||
  formValue["vendor"] === null ||
  formValue["vendor"].trim() === ""
 ) {
  $("[formControlName='department']").focus();
  $("[formControlName='employee']").focus();
  $("[formControlName='vendor']").focus();

  this.noEmployeesFound = true;
  this.noDepartmentsFound = true;
  this.noVendorsFound = true;

  return false;
 }
}

Check out this screenshot of the form where I implemented this code

Answer №1

Give this a shot.

Let's try this: formValue.employee.toString().trim()

Answer №2

Give this a try for assistance:

    pattern: any;
        ngOninit() {
    this.pattern = "^\S{0,50}$";
//you can utilize this pattern to prevent spaces at the beginning and end "^[^\s]+(\s+[^\s]+)*$"
              this.telephoneForm = this.formBuilfer.group({
                employee: [null, Validators.pattern(this.pattern), Validators.required ],
        })
        }

The pattern above will not allow spaces in the input field and will display an error message in HTML like:

<div *ngIf="employee.errors?.pattern">
    employee is not valid.
</div> 

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

Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below: export enum SomeErrorCodes { none = 0, notFound = 1, duplicated = 2 } Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

React Router throwing an error about an Invalid Hook Call when attempting to use useState in index.tsx instead of App.js

I'm currently learning React Router by following a video tutorial, but I've run into an issue. In my Stackblitz project, there is no App.js file, so I've placed everything inside index.tsx. However, now I need to use the line ----> const ...

Having trouble compiling my Angular application with success

I am working with a file named mock-values.ts. In this file, I have defined the following constants: export const TIMES: Time[] = [ { i: '8:00', v: '8' }, { i: '8:30', v: '8:30' }, { i: '9:00', v: &apo ...

What is the process for adjusting the color of a mat-divider?

Has anyone been successful in changing the color of mat-divider? I attempted the following but had no luck: component.html <mat-divider class="material-devider"></mat-divider> component.scss .material-devider { color: red } ...

The exported instance of sequelize is missing in the Module imports

Good evening! I currently have an express server with a main script that includes the following export: export const sequelize = new Sequelize( 'postgres', config.db_user, config.db_password, { host: 'localhost', port: config ...

Trouble with z-index property within the confines of the <ion-segment-button></ion-segment-button> tag

The z-index property seems to be having no effect on the elements within the ion-segment-button. I attempted to adjust the positions of the elements and set the z-index to 999999 with the button z-index set to -1. However, this solution did not work as ex ...

What is the best approach to managing exceptions consistently across all Angular 2/ Typescript observables?

Throughout the learning process of Angular2, I have noticed that exceptions are often caught right at the point of the call. For example: getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() ...

Is there a missing .fillGeometry in the Figma plugin VectorNode?

The documentation for VectorNode mentions a property called fillGeometry. Contrary to this, TypeScript indicates that "property 'fillGeometry' does not exist on type 'VectorNode'". https://i.sstatic.net/ICfdw.png I seem to be missing ...

Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. T ...

Using Mongo Node Angular all in one server

Is it advisable to host Angular, Node-express, and Mongo on the same server, such as localhost:3000 or somehosting.com/server-address? Would this be considered a best practice? I have seen Angular and Node running together on the same server, but what abo ...

Issue updating @angular/core in Angular CLI caused by rxjs dependency

Currently, I am in the process of updating angular and angular material to version 6. I have successfully updated the cli to allow for the new ng update command. However, when attempting to use it to update @angular/core, I encounter an error stating that ...

Develop Connective Plugins using Angular 12

I am working on implementing a new feature for my app that involves storing certain modules on the backend and loading them dynamically based on user demand. Instead of loading all modules at once, I want to only load the necessary modules just before the ...

Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the app/App_Resources/Android/app.gradle file: // Uncomment to add recyclerview-v7 dependency dependencies ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...

App crashing when attempting to display an undefined value in an Ionic/Angular 2 application

Uncertain whether the issue lies with ionic or angular specifically. The use of {{ }} is unfamiliar, making it difficult to find a solution. Simple HTML layout: <ion-content padding> <ion-card> <ion-card-content> <ion-row ...

Unexpected Typescript error when React component receives props

I encountered an unexpected error saying ": expected." Could it be related to how I'm setting up props for the onChange event? Here is my code for the component: import React from "react"; interface TextFieldProps { label?: string; ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Using Angular to make an HTTP POST request to fetch data

My trusty .net backpack has been working flawlessly. However, I encountered an issue when trying to connect it with the Angular front end. All backend requests are post requests and require passing an ApiKey in the body of each request. Interestingly, ever ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...