Dot Net Help

Dot Net Help Contact information, map and directions, contact form, opening hours, services, ratings, photos, videos and announcements from Dot Net Help, Amrakunj society, Ahmedabad.

26/02/2024

Angular 8 | Template Driven Form Validation Tutorial by Example

In this tutorial, we will discuss how to add a form using Angular Material Form controls with validation. The form will have a text field, select dropdown and radio control to select an option from.

In Angular we have two types of Forms available:

Template Driven Form
Reactive Forms

Here we will focus on creating Angular Template Driven Form with required controls and Validation behavior. Let’s implementation from start by creating a new Angular 8 project than adding Angular Material to it.

Create an Angular Project
Make sure you have the latest version of Angular CLI installed.

$ npm install -g /cli
Create a new project using Angular CLI tool by running following command

$ ng new angular-form-validation
? Would you like to add Angular routing? = Yes
? Which stylesheet format would you like to use? = CSS

$ cd angular-form-validation
Install Angular Material
As we are creating a v8 Angular project, so we need the same version for Angular Material. Run following NPM command to install Angular Material and it's dependencies

# Install material, CDK and animations
$ npm install --save /material /cdk /animations


Configure Material Animations
Next, open app.module.ts file to import BrowserAnimationsModule then add it in imports array to enable animation for Material components.

//app.module.ts
import { BrowserModule } from '/platform-browser';
import { NgModule } from '/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '/platform-browser/animations';

({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Add Material Theme
To add a theme of Material in the project, open styles.css file then import one of the theme file used to style Material components.

/* styles.css */
/* You can add global styles to this file, and also import other style files */
"~/material/prebuilt-themes/indigo-pink.css";
We are done with Angular material installation and configurations.

Import Material Modules
To use Angular Material form controls, we need to import them in the app's module file so that they are available anywhere in our application.

In our Form, we will be having Input, Select Dropdown, Radio buttons and also Form field module used to wrap textarea, input, select, etc.

Also, we have used SnackBar, it is like a toast message which shows information message to the user on a floating container on view.

So after making the required imports, our app.module.ts file will look like this:

//app.module.ts
import { BrowserModule } from '/platform-browser';
import { NgModule } from '/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '/platform-browser/animations';

import {
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatRadioModule,
MatButtonModule,
MatSnackBarModule
} from '/material';

import { FormsModule } from '/forms';

({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,

FormsModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatRadioModule,
MatButtonModule,
MatSnackBarModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
If you notice above, we also having FormsModule, as we will use the ngForm directive to control form validation.

Add Form and Form Controls
Finally, we are ready to add a form in App component template app.component.html file

In form tag (ngSubmit) event handler is calling the submitForm method to handle form data.

is used to wrap some of the controls like here we wrapped Input and Select. But we can't use it to wrap Radio controls.

Learn more
That's why we added a custom validation handler login on by wrapping it in a custom div with ngClass.








Select Designation

Select Designation

{{des.value}}






Male
Female




Submit


For Radio Group validation to show red color text we need to add some CSS in styles.css making it highlight if the value is not selected.
mat-form-field-invalid .mat-radio-label-content{
color: ;
}mat-form-field-invalid .mat-radio-outer-circle{
border-color: !important;
}
In the app.component.ts file, we have a list of designation options and submitFrom method which will check if the form is valid using template variable reference we got using

//app.component.ts
import { Component, OnInit, ViewChild } from '/core';
import { NgForm } from '/forms';
import { MatSnackBar } from '/material/snack-bar';

export interface Designation {
id: string;
value: string;
}

({
selector: 'app-formvalidation',
templateUrl: './formvalidation.component.html',
styleUrls: ['./formvalidation.component.css']
})
export class FormvalidationComponent implements OnInit {

('myForm',{static:false}) public MyForm: NgForm;

fname:string;

formData = {
name:"",
designation:"",
gender:"",
}

constructor(private _snackBar: MatSnackBar) { }

ngOnInit() {
}

designations: Designation[] = [
{id: '1', value: 'Developer'},
{id: '2', value: 'Senior Programmer'},
{id: '3', value: 'Software Architect'}
];

submitForm(e){
console.log(this.MyForm);
if(this.MyForm.valid){
//Submit form logic here!
}else{
this._snackBar.open("Please fill all fields","",{duration:1000});
}
}

}
The form will look like this:

Conclusion: We discussed how to implement a simple template-driven form using Angular Material controls with validation. Here we also added Radio group with validation using custom class.

23/08/2022

Sorting string 1.1 , 1.2,1.3 ,1.10 in proper

select VersionNo from Versions order by cast('/' + replace(VersionNo , '.', '/') + '/' as hierarchyid);

11/03/2021

QUESTION:

I have a varchar2 column in a table, values only contain number and DOT and no two or more continuous DOTs. the value looks like following:
1
1.1
1.1.1
1.1.2
1.2
1.2.4
1.2.5
1.2.10
1.10.1
1.10.2..

I want to sort this column by individual number separated by Dot. below is the result I want:
1
1.1
1.1.1
1.1.2
1.2
1.2.4
1.2.5
1.2.10
1.10.1
1.10.2

NOT
1
1.1
1.1.1
1.1.2
1.10.1
1.10.2
1.2
1.2.10
1.2.4
1.2.5

Is there any easy way to do it? Can I just use any Oracle built-in functions to do it? But I don't want to create a customized function to process the column and then sort in the select statement, e.g. select * from TableA order by functionA(ColumnA).

create table t (col varchar2(30));
insert into t values ('1');
insert into t values ('1.1');
insert into t values ('1.1.1');
insert into t values ('1.1.2');
insert into t values ('1.2');
insert into t values ('1.2.4');
insert into t values ('1.2.5');
insert into t values ('1.2.10');
insert into t values ('1.10.1');
insert into t values ('1.10.2');
insert into t values ('2');
insert into t values ('2.1');
commit;

ANSWER:::::::::::::::::::::::::::::::::::::::::::::::::::::::

select col,
2 to_number(substr( '.'||col||'.',
3 instr( '.'||col||'.', '.', 1, 1 )+1,
4 instr( '.'||col||'.', '.', 1, 2 )-instr( '.'||col||'.', '.', 1, 1 )-1 )) c1 ,
5 to_number(substr( '.'||col||'.',
6 instr( '.'||col||'.', '.', 1, 2 )+1,
7 instr( '.'||col||'.', '.', 1, 3 )-instr( '.'||col||'.', '.', 1, 2 )-1 )) c2 ,
8 to_number(substr( '.'||col||'.',
9 instr( '.'||col||'.', '.', 1, 3 )+1,
10 instr( '.'||col||'.', '.', 1, 4 )-instr( '.'||col||'.', '.', 1, 3 )-1 )) c3
11 from t
12 order by
13 to_number(substr( '.'||col||'.',
14 instr( '.'||col||'.', '.', 1, 1 )+1,
15 instr( '.'||col||'.', '.', 1, 2 )-instr( '.'||col||'.', '.', 1, 1 )-1 ))
16 nulls first,
17 to_number(substr( '.'||col||'.',
18 instr( '.'||col||'.', '.', 1, 2 )+1,
19 instr( '.'||col||'.', '.', 1, 3 )-instr( '.'||col||'.', '.', 1, 2 )-1 ))
20 nulls first,
21 to_number(substr( '.'||col||'.',
22 instr( '.'||col||'.', '.', 1, 3 )+1,
23 instr( '.'||col||'.', '.', 1, 4 )-instr( '.'||col||'.', '.', 1, 3 )-1 ))
24 nulls first
25 /

COL C1 C2 C3
------------------------------ ---------- ---------- ----------
1 1
1.1 1 1
1.1.1 1 1 1
1.1.2 1 1 2
1.2 1 2
1.2.4 1 2 4
1.2.5 1 2 5
1.2.10 1 2 10
1.10.1 1 10 1
1.10.2 1 10 2
2 2
2.1 2 1

12 rows selected.

12/09/2020
If your web app is being hosted over HTTPs as you've indicated, then all external resources it is consuming (CDN, script...
25/06/2019

If your web app is being hosted over HTTPs as you've indicated, then all external resources it is consuming (CDN, scripts, CSS files, API calls) should also use SSL and be secured through HTTPs. Think about it. It would defeat the purpose of your app being secure, if your app was in turn making insecure requests to an API.
You can either therefore:

1 > As Chrome suggests, change your API calls to use HTTPs (recommended)
2 > Use HTTP instead of HTTPs
3 > Add the following meta tag to your element in your HTML:



More information about this can be found here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests.

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers o...

21/02/2019

How to call WCF Service method using List of Class as parameter

function GetTest() {

var aa = {
"NewsId": 1,
"Title": "testtitle",
"ShortDescription": "TestShortDescription",
"Link": "LinkLink",
"Keywords": "testKeywords",
};
var abc = [];
abc.push(aa);

$.ajax({

contentType: 'application/json',
data: JSON.stringify({
lstGetTop: abc
}),
dataType: "json",
type: "POST",
url: "/WCFServices/News.svc/GetTest",
success: function (Result) {

}
});
}

----------------------------- IN SIDE WCFService -------------------

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public string GetTest(List lstGetTop)
{
return "";
}

24/10/2018

Sending Email Using SQL server

--- Step - 1
EXEC msdb.dbo.sysmail_add_account_sp
= 'none'
, = 'Sending SMTP mails to users'
, = 'www.email.com'
, = ''www.email.com'
, = ''www.email.com'
, = 'smtp.gmail.com'
, = 587
, = 1 -- This is by default 0 If you want to enable ssl then type 1
, = ''www.email.com'
, = 'www.email.com'
Go

select * from msdb.dbo.sysmail_server
--- Step - 2
--------------------------------------------
EXEC msdb.dbo.sysmail_add_profile_sp
= ''www.email.com'
, = 'Sending SMTP mails to users'
Go
--- Step - 3
----------------------------------------
EXEC msdb.dbo.sysmail_add_profileaccount_sp
= ''www.email.com'
, = ''www.email.com'
, = 1
GO

--- Step - 4 sample email
EXEC msdb.dbo.sp_send_dbmail
= ''www.email.com'
, = ''www.email.com'
, = 'Automated Test Results Oye Oye (Successful)'
, = 'The stored procedure finished successfully.'
, ='HIGH'
GO

25/04/2018

ASP.NET has built-in request validation that automatically helps protect against XSS and HTML injection attacks. If you want to explicitly disable this validation you could decorate the action you are posting to with the [ValidateInput(false)] attribute:

[HttpPost]
[ValidateInput(false)]
public ActionResult SaveArticle(ArticleModel model)
{
var JResult = new JsonResult();
if (ModelState.IsValid)
{
...
}
return JResult;
}

Also if you are running this on ASP.NET 4.0 for this attribute to take effect you need to add the following to your web.config:



And if you are using ASP.NET MVC 3.0 you could decorate only the property on your model that requires HTML with the [AllowHtml] attribute:

public class ArticleModel
{
[AllowHtml]
public string SomeProperty { get; set; }

public string SomeOtherProperty { get; set; }
}

Also in your javascript function you probably want serialize() instead of serializeArray():

function JqueryFromPost(formId) {
var form = $(formId);
$.post(form.action, form.serialize(), function (data) {
//Getting the data Result here...
});
}

19/04/2018







$(document).ready(function(){

$(' ').click(function () {

// Checking whether FormData is available in browser
if (window.FormData !== undefined) {

var fileUpload = $(" ").get(0);
var files = fileUpload.files;

// Create FormData object
var fileData = new FormData();

// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}

// Adding one more key to FormData object
// fileData.append('username', ‘Manas’);

$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});

});

[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);

HttpPostedFileBase file = files[i];
string fname;

// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}

// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Address

Amrakunj Society
Ahmedabad
382721

Telephone

9712146525

Website

Alerts

Be the first to know and let us send you an email when Dot Net Help posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Share