<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="https://publishpress.com/"
	>

<channel>
	<title>Validations Archives - 아빠프로그래머의 좌충우돌 개발하기!</title>
	<atom:link href="https://www.daddyprogrammer.org/post/tag/validations/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.daddyprogrammer.org/post/tag/validations/</link>
	<description>기저귀 갈면서 코딩해야 프로다!</description>
	<lastBuildDate>Thu, 17 Feb 2022 09:53:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://www.daddyprogrammer.org/wp-content/uploads/2019/04/cropped-spring-bird-2295431_960_720-300x300.jpg</url>
	<title>Validations Archives - 아빠프로그래머의 좌충우돌 개발하기!</title>
	<link>https://www.daddyprogrammer.org/post/tag/validations/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Angular2 정리(5) – Validations</title>
		<link>https://www.daddyprogrammer.org/post/4054/anguar2-validations/</link>
					<comments>https://www.daddyprogrammer.org/post/4054/anguar2-validations/#comments</comments>
		
		<dc:creator><![CDATA[happydaddy]]></dc:creator>
		<pubDate>Fri, 17 May 2019 17:09:20 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[AngularJS]]></category>
		<category><![CDATA[Validations]]></category>
		<guid isPermaLink="false">http://3.36.120.4/?p=4054</guid>

					<description><![CDATA[<p>이번 장에서는 폼에 입력된 값의 유효성을 체크하는 방법에 대해 실습하겠습니다. Input 필드의 값 유효성 체크 ngModel을 사용해야 하므로 FormsModule을 app.module.ts에 선언합니다. Component html파일에 다음과 같이 input을 선언합니다. [(ngModel)]은 양방향 바인딩을 하기 위해 사용됩니다. 예제에서는 괄호를 모두 없애고 ngModel만 사용하였는데 이렇게 사용하면 input에 validation이 적용됩니다. 예제에서는 required를 사용하여 input값이 필수인 유효성 체크를 적용하였습니다. div에 *ngIf을 사용하여 [&#8230;]</p>
<p>The post <a href="https://www.daddyprogrammer.org/post/4054/anguar2-validations/">Angular2 정리(5) – Validations</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">이번 장에서는 폼에 입력된 값의 유효성을 체크하는 방법에 대해 실습하겠습니다.</p>



<h3 class="wp-block-heading">Input 필드의 값 유효성 체크</h3>



<p class="wp-block-paragraph">ngModel을 사용해야 하므로 FormsModule을 app.module.ts에 선언합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// app.module.ts
import { FormsModule } from '@angular/forms';
... 생략
imports: [
    FormsModule
  ]</pre>



<p class="wp-block-paragraph">Component html파일에 다음과 같이 input을 선언합니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;input ngModel required #name=ngModel />
&lt;div *ngIf="name.touched &amp;&amp; !name.valid">
    Name field is required!
&lt;/div></pre>



<p class="wp-block-paragraph">[(ngModel)]은 양방향 바인딩을 하기 위해 사용됩니다. 예제에서는 괄호를 모두 없애고 ngModel만 사용하였는데 이렇게 사용하면 input에 validation이 적용됩니다. 예제에서는 required를 사용하여 input값이 필수인 유효성 체크를 적용하였습니다.</p>



<p class="wp-block-paragraph">div에 *ngIf을 사용하여 유효성 검사가 실패할경우 오류 메시지를 출력할 수 있습니다. input에 #name=ngModel라고 선언하면 해당 태그의 유효성 여부를 name값을 통해 얻을수 있습니다. 예제에서는 name.touched &amp;&amp; !name.valid 두가지 조건으로 유효성을 판단하는데 첫번째 조건은 input에 커서가 한번이라도 포커싱 되었었는지를 판단합니다. name.touched를 조건에 포함시키지 않으면 페이지가 최초 로드될때 오류 메시지가 출력됩니다. </p>



<p class="wp-block-paragraph">입력값이 유효한지(값이있는지)를 체크하는것은 두번째 조건( !name.valid )에 의해서입니다.<br>required를 적용하였으므로 빈값일 경우 name.valid = false를 반환합니다. 만약 input에 값을 입력하면 에러메시지는 자동으로 사라집니다.</p>



<figure class="wp-block-image is-resized"><img decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate.png" alt="" class="wp-image-5891" width="159" height="50" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate.png 159w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-150x47.png 150w" sizes="(max-width: 159px) 100vw, 159px" /></figure>



<h3 class="wp-block-heading">유효성 체크 종류</h3>



<p class="wp-block-paragraph">angular에서 기본으로 지원하는 유효성 체크는 아래와 같습니다. 상세한 내용은 링크를 참고하면 됩니다.  <a rel="noreferrer noopener" aria-label=" (새탭으로 열기)" href="https://angular.io/api/forms/Validators" target="_blank">https://angular.io/api/forms/Validators</a> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Validators {
  static min(min: number): ValidatorFn
  static max(max: number): ValidatorFn
  static required(control: AbstractControl): ValidationErrors | null
  static requiredTrue(control: AbstractControl): ValidationErrors | null
  static email(control: AbstractControl): ValidationErrors | null
  static minLength(minLength: number): ValidatorFn
  static maxLength(maxLength: number): ValidatorFn
  static pattern(pattern: string | RegExp): ValidatorFn
  static nullValidator(control: AbstractControl): ValidationErrors | null
  static compose(validators: ValidatorFn[]): ValidatorFn | null
  static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
}</pre>



<h3 class="wp-block-heading">다수의 유효성 체크</h3>



<p class="wp-block-paragraph">폼 안에 여러개의 조건을 넣어서 유효성 체크가 가능합니다.<br>아래 예제에서는 다음 3개의 내용에 대한 유효성 체크를 하고 있습니다.</p>



<ul class="wp-block-list"><li>무조건 값이 입력되어야 한다.</li><li>글자는 최소 5글자 최대 30글자 이내로 작성해야 한다.</li><li>이메일 형식에 맞게 입력해야 한다. </li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Email : &lt;input ngModel #email=ngModel required minlength=5 maxlength=30
    pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">
&lt;div *ngIf="email.touched &amp;&amp; !email.valid">
    &lt;div *ngIf="email.errors['required']">email is required&lt;/div>
    &lt;div *ngIf="email.errors['minlength']">email is is should have a least 10 characters&lt;/div>
    &lt;div *ngIf="email.errors['pattern']">email pattern is mismatch&lt;/div>
&lt;/div></pre>



<p class="wp-block-paragraph">여러개의 유효성 체크를 적용한경우 유효성 결과를 배열( email.errors )을 통해 알수 있어 상황별로 메시지 처리를 할 수 있습니다.</p>



<figure class="wp-block-image is-resized"><img decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/validate_1.png" alt="" class="wp-image-5902" width="206" height="47" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/validate_1.png 206w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/validate_1-150x34.png 150w" sizes="(max-width: 206px) 100vw, 206px" /><figcaption> 입력창에 입력없이 빠져나온경우. </figcaption></figure>



<figure class="wp-block-image is-resized"><img decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-2.png" alt="" class="wp-image-5898" width="295" height="66" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-2.png 295w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-2-150x34.png 150w" sizes="(max-width: 295px) 100vw, 295px" /><figcaption>입력 글자수가 조건에 일치하지 않는 경우.<br>이메일 형식 체크.</figcaption></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-3.png" alt="" class="wp-image-5899" width="208" height="48" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-3.png 208w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/required-validate-3-150x35.png 150w" sizes="auto, (max-width: 208px) 100vw, 208px" /><figcaption>이메일 형식이 틀린경우.</figcaption></figure>



<h3 class="wp-block-heading">그룹 유효성 체크</h3>



<p class="wp-block-paragraph">지금까지는 단일 객체에 대해서만 유효성을 체크하였지만, 그룹으로도 유효성 체크가 가능합니다. </p>



<p class="wp-block-paragraph">예제에서는 이름과 이메일을 입력받는데 둘중 하나의 입력값이 유효하지 않을경우 오류 메시지를 발생시키고 submit버튼을 비활성화 처리 합니다.</p>



<p class="wp-block-paragraph">그룹핑은 &lt;form&gt; 태그안에 ngModelGroup을 사용하여 그룹핑 할수 있고  그룹내에 포함되어있는 Form객체들에 대한  유효성을 체크할 수 있습니다.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;form>
  &lt;div ngModelGroup="contact" #contact=ngModelGroup>
    &lt;div *ngIf="firstName.touched &amp;&amp; email.touched &amp;&amp; contact.invalid">You may miss some contact information&lt;/div>
    &lt;label for="firstName">FirstName&lt;/label>&lt;br>
    &lt;input required ngModel name="firstName" #firstName=ngModel>
    &lt;div *ngIf="firstName.touched &amp;&amp; !firstName.valid">Name field is required!&lt;/div>
    &lt;br>
    &lt;label for="email">email&lt;/label>&lt;br>
    &lt;input required ngModel minlength="3" maxlength="20" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
        name="email" #email=ngModel>
    &lt;div *ngIf="email.touched &amp;&amp; !email.valid">
        &lt;div *ngIf="email.errors['required']">email is required&lt;/div>
        &lt;div *ngIf="email.errors['minlength']">email should have at least 3 characters&lt;/div>
        &lt;div *ngIf="email.errors['pattern']">pattern is mismatch&lt;/div>
    &lt;/div>&lt;br>
    &lt;button [disabled]="contact.invalid">submit&lt;/button>
  &lt;/div>
&lt;/form></pre>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_1.png" alt="" class="wp-image-5968" width="282" height="165" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_1.png 282w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_1-150x88.png 150w" sizes="auto, (max-width: 282px) 100vw, 282px" /><figcaption>이메일 형식이 맞지 않을때</figcaption></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_2.png" alt="" class="wp-image-5969" width="281" height="163" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_2.png 281w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_2-150x87.png 150w" sizes="auto, (max-width: 281px) 100vw, 281px" /><figcaption>FirstName을 입력하지 않았을때</figcaption></figure>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="http://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_3.png" alt="" class="wp-image-5970" width="146" height="108" srcset="https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_3.png 146w, https://www.daddyprogrammer.org/wp-content/uploads/2019/07/chk_3-80x60.png 80w" sizes="auto, (max-width: 146px) 100vw, 146px" /><figcaption>정상적으로 입력하였을경우 버튼이 활성화 된다.</figcaption></figure>
<p>The post <a href="https://www.daddyprogrammer.org/post/4054/anguar2-validations/">Angular2 정리(5) – Validations</a> appeared first on <a href="https://www.daddyprogrammer.org">아빠프로그래머의 좌충우돌 개발하기!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.daddyprogrammer.org/post/4054/anguar2-validations/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<series:name><![CDATA[Angular2 알아보기]]></series:name>
	</item>
	</channel>
</rss>
