Angular Form Validation no Whitespace Allowed

In this section, we are going to learn about form validation. In this form, we will not allow any white space. We will use Angular to do this. Many times, our application needs a form that accepts input without any space. In our reactive form, we can use custom validation which will not allow whitespace. Using this custom validation, we can easily validate no whitespace allowed. In order to validate that no whitespace is allowed, we can use various versions of Angular like Angular 6, 7, 8, 9, 10, and 11.

If we try to add validation for not allowing any white space in our form by using "if condition" or any other things. But this way is very difficult. So we found a simple way to validate that no whitespace is allowed. We will create custom validation, which contains a lot of rules to validate this. In our below example, new custom validation will be created, which will not allow containing space on the input field. In our form, the username will not allow entering with space. In order to do this, we have to follow some steps, which are described as follows:

Step 1:

In this step, we are going to Install Angular app. Here, we will create a new ng-app. We do not need to create an Angular app if we have already created it. In order to create the new ng-app, the following command will be used like this:

Step 2:

In this step, we are going to Import FormsModule. In our Angular app, we need to create a form. We will use the @angular/forms library to import it. Now we will use a file named app.module.ts and add the following code into it:

src/app/app.module.ts

Step 3:

In this step, we are going to Create Form with ngModel. Here, the code of an HTML form will be written. In this form, we will use the Bootstrap class. If we don't have Bootstrap, we can use the following link to install it in our system:

https://www.javatpoint.com/angular-7-with-bootstrap#:~:text=How%20to%20install%20Bootstrap%20for,%3E%20The%20%403%20is%20important!

Now we will use a file named app.component.html and add the below code into it like this:

src/app/app.component.html

Step 4:

In this step, we are going to Update Ts File. This file is used to write submit(). It is also used to get all the values of input fields. Now we will use a file named app.component.ts and add the below code into it like this:

src/app/app.component.ts

Step 5:

In this step, we are going to Create Custom Validation File. Here, we will create a custom file named "username.validator.ts", and then we will add the following code into it like this:

src/app/username.validator.ts

Now our above code is ready to run. In order to run the above code, we will use the following command:

When we run this command, the following output will be generated:

Angular Form Validation no Whitespace Allowed




Latest Courses