Introduction
This article is going to explain how to apply input validations to a form. We have used Angular 6 directive to perform that using Visual Studio Code. Let's see how we can do that with step by step instructions.
Background
- If you love to start with .NET Core on a Linux server, check what are the basic things you have to do, Install .NETCore in a Linux server
- Say Hello from .NET Core application in a Linux server,.NET Core with a Linux server: Hello World!
- If you are interested in open source platforms and want to try out .NET Core application development in Linux, try with these steps,.NETCore: Create a web application with a Linux server
- If you want to know how to create an ASP.NET Core service application check this article,ASP.NETCore: Create a Web API application
- If you want to show a loading panel on the screen using ASP.NET Core, go through this article, ASP.NET Core : How to show a loading panel in a page
- If you like to use template generators for .NET Core this is the ideal article for you, .NET Core: Create web application with Yeoman template generator
- When you are developing ASP.NET Core web applications, security is a crucial thing, follow this article to know more about it, Secure your .NETCore web applications using IdentityServer 4
- Check how to show a confirmation dialog with jquery from this post, ASP.NET Core : How to show a confirmation dialog with jquery
- If you want to try out advanced features in jquery dialog on top of .NET Core, this will be a great article for you, ASP.NET Core : Advanced JQuery dialog actions
- If you are interested in user authentication & ASP.NET Identity follow this link, ASP.NET Identity: Customize User Authentication
- You can send a simple smtp email by checking this article, C#: Create a simple SMTP email with HTML body
- Check this article to know how to use a windows service to fire an email How to fire an email using a windows service
- If you ever want to log error messages, warning or any information in your application, you have to select a logging framework, Go through this article and learn what are the available logging frameworks, Log messages using NLog framework
- Check this article and learn how to use hashing and salting to protect your passwords, keys C#: How to generate a unique key or password using salting + hashing
- If you are a LINQ query fan and want to know few basic tricks, this is the article for you LINQ - list update tricks
- If you are interested to follow on ODATA queries, check this article ODATA Reads with Parameters
- Go through ODATA Reads to know about read queries with ODATA
- If you are interested to know about Azure storage, blobs check this article,Send smtp email with Azure blob storage attachments
- We are going to create a Function app and publish that in Azure, if you are curious to know more about Azure functions check this one, Azure Function App: Create a trigger on Cosmos DB
- If you are interested in Microsoft Graph and want to know more about Outlook API, check this article, NET Core: Building Function app with Microsoft Graph API and Azure Functions
- If you like to know about Microsoft Graph and how we can integrate our business solution with it, go through this article, .NET Core: Process a Excel file with Microsoft Graph API & Azure Function
- Check this article and get to know how to work with Azure Cosmos DB - Document API,Explore Azure Cosmos DB - document API
- Learn how to map your on premise database in to a cloud NOSQL based database, Azure Cosmos DB: Designing your data structure
- You can see a how to load a partial view using ASP.NET MVC ASP.NET Core MVC: How to load a partial view
- You can go through this article and see how to apply input value restrictions to textboxes ising Angular 6, Visual Studio: Input restrictions in a form with Angular 6
Create Angluar application
You can see the sample web page in the browser like this,
You can see app.component.html file as below, it has a form to get input values, it's going to check for mandatory fields like First name, Last name, Email, SSN and Gender.
All of these fields have required attribute, angular directive is used to check whether input values are given in correct format with the help of a regular expression.
We are going to use directives to apply the validation, so directives are added to app.module component as below. PhoneVaidator, EmailValidator and SSNValidator.
import {PhoneValidator} from './directives/input-validators/phone-validator.directive';
import {EmailValidator} from './directives/input-validators/email-validator.directive';
import {SSNValidator} from './directives/input-validators/ssn-validator.directive';
@NgModule({
declarations: [
AppComponent,
PhoneValidator,
EmailValidator,
SSNValidator
],
imports: [
BrowserModule,
FormsModule,
NgSelectModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
You can see the directive to apply email validation as follows, It's going to use a regular expression to parse the input text in the email field.
//validate email
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms';
import { Directive } from '@angular/core';
@Directive({
selector: '[emailvalidator][ngModel]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: EmailValidator,
multi: true
}
]
})
export class EmailValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = this.emailValidator();
}
validate(c: FormControl) {
return this.validator(c);
}
emailValidator(): ValidatorFn {
return (c: FormControl) => {
if(c.value == "") {
return null;
}
let isValid = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/ .test(c.value); //email
if (isValid) {
return null;
} else {
return {
emailvalidator: {
valid: false
}
};
}
}
}
}
We can validate
Phone no field using this
regular expression, It allows to enter
phone no in
+11111111111 format.
//validate phone no
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms';
import { Directive } from '@angular/core';
@Directive({
selector: '[phonevalidator][ngModel]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: PhoneValidator,
multi: true
}
]
})
export class PhoneValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = this.phoneValidator();
}
validate(c: FormControl) {
return this.validator(c);
}
phoneValidator(): ValidatorFn {
return (c: FormControl) => {
if(c.value == "") {
return null;
}
let isValid = /^\+[0-9]{11}$/.test(c.value);
if (isValid) {
return null;
} else {
return {
phonevalidator: {
valid: false
}
};
}
}
}
}
We want to validate
SSN field in Norway, so have to install
npm package to validate
ssn field as below,
npm install --save norwegian-national-id-validator
You can find the following directive has used installed npm package to validate
norwegian ssn no
//validate ssn
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms';
import { Directive } from '@angular/core';
import { validateNorwegianIdNumber } from 'norwegian-national-id-validator';
@Directive({
selector: '[ssnvalidator][ngModel]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: SSNValidator,
multi: true
}
]
})
export class SSNValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = this.ssnValidator();
}
validate(c: FormControl) {
return this.validator(c);
}
ssnValidator(): ValidatorFn {
return (c: FormControl) => {
if(c.value == "") {
return null;
}
let isValid = /^[0-9]{6}( )[0-9]{5}$/g.test(c.value);
if (isValid) {
var format = validateNorwegianIdNumber(c.value.replace(/ /g,''));
if(format){
return null;
}
else{
return {
ssnvalidator: {
valid: false
}
};
}
} else {
return {
ssnvalidator: {
valid: false
}
};
}
}
}
}
You can see
package.json file like this after installing npm package to validate
ssn field
When you run the application, you can see
Create Student form as below,
Save button is disabled since the form is not
dirty yet.
When you hit on the
Save button after entering some values, You can see all the
required field error messages as follows, It shows
SSN and
Email fields as
invalid as well.
It doesn't show
Phone as
invalid since we haven't added any value to it and
Phone is not a mandatory field.
You can see Gender dropdown field has turned into red border as above, we have to add some styling to achieve that.
.invalid-feedback-select {
width: 100%;
font-size: 80%;
color: #dc3545;
}
We have to add style file in angular.json file
"styles": [
"./node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css",
"src/assets/css/common.scss"
],
Let's input data to required fields and check what happens, still shows invalid fields as below for phone no, email and ssn
After entering correct values for Phone, Email and SSN form look like this.
Download
TechNet Gallery
Conclusion
In this article, it describes how to apply input validations to form controls using Angular 6. The sample code has used .NET Core Web API project to develop the service layer. We used Angular 6 directives to achieve this.
References