■ TextFormField 클래스의 validator 속성을 사용해 입력 값을 검증하는 방법을 보여준다. ▶ main.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
import 'package:flutter/material.dart'; void main() => runApp(TestApplication()); class TestApplication extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Test Application', home: Scaffold( appBar: AppBar( title: Text('Test Application'), ), body: MainPage(), ), ); } } class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextFormField( validator: (value) { if (value.isEmpty) { return '주소를 입력해 주시기 바랍니다.'; } return null; }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: RaisedButton( child: Text('검증'), onPressed: () { if (_formKey.currentState.validate()) { Scaffold.of(context).showSnackBar(SnackBar(content: Text('정상적으로 입력되었습니다.'))); } }, ), ), ], ), ), ); } } |
■ Form 클래스에서 입력 값을 검증하는 방법을 보여준다. ▶ main.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
import 'package:flutter/material.dart'; void main() => runApp(TestApplication()); class TestApplication extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Test Application', home: Scaffold( appBar: AppBar( title: Text('Test Application'), ), body: MainPage(), ), ); } } class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextFormField( validator: (value) { if (value.isEmpty) { return '주소를 입력해 주시기 바랍니다.'; } return null; }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: RaisedButton( child: Text('검증'), onPressed: () { if (_formKey.currentState.validate()) { Scaffold.of(context).showSnackBar(SnackBar(content: Text('정상적으로 입력되었습니다.'))); } }, ), ), ], ), ), ); } } |
test_app.zip
■ ControllerBase 클래스의 StatusCode 메소드를 사용해 검증 오류를 처리하는 방법을 보여준다. ▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllers(); } ); } #endregion } } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Docs.Samples; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> [ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public // GET /api/test/3 #region 구하기 - Get(id) /// <summary> /// 구하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과</returns> [HttpGet("{id}")] public IActionResult Get(string id) { if(id.Contains('0')) { return StatusCode(StatusCodes.Status406NotAcceptable); } return ControllerContext.MyDisplayRouteInfo(id); } #endregion } } |
TestProject.zip
■ IValidateOptions<T> 인터페이스를 사용해 복잡한 유효성을 검사하는 방법을 보여준다. ▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
{ "Test" : { "Key1" : "Key One", "Key2" : 40, "Key3" : 30 }, "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
▶ Models/TestOption.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
namespace TestProject.Models { /// <summary> /// 스타일 옵션 /// </summary> public class TestOption { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 키 1 - Key1 /// <summary> /// 키 1 /// </summary> public string Key1 { get; set; } #endregion #region 키 2 - Key2 /// <summary> /// 키 2 /// </summary> public int Key2 { get; set; } #endregion #region 키 3 - Key3 /// <summary> /// 키 3 /// </summary> public int Key3 { get; set; } #endregion } } |
▶ Models/TestValidation.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
using Microsoft.Extensions.Options; using System.Text; using System.Text.RegularExpressions; namespace TestProject.Models { /// <summary> /// 테스트 검증 /// </summary> public class TestValidation : IValidateOptions<TestOption> { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestValidation() /// <summary> /// 생성자 /// </summary> public TestValidation() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 검증하기 - Validate(name, option) /// <summary> /// 검증하기 /// </summary> /// <param name="name">명칭</param> /// <param name="option">옵션</param> /// <returns>검증 옵션 결과</returns> public ValidateOptionsResult Validate(string name, TestOption option) { StringBuilder stringBuilder = new StringBuilder(); Regex regex = new Regex(@"^[a-zA-Z''-'\s]{1,40}$"); var match = regex.Match(option.Key1); if(string.IsNullOrEmpty(match.Value)) { stringBuilder.AppendLine($"{option.Key1} doesn't match RegEx"); } if(option.Key2 < 0 || option.Key2 > 1000) { stringBuilder.AppendLine($"{option.Key2} doesn't match Range 0 - 1000"); } if(option.Key2 != default) { if(option.Key3 <= option.Key2) { stringBuilder.AppendLine("Key3 must be > than Key2."); } } if(stringBuilder.Length > 0) { return ValidateOptionsResult.Fail(stringBuilder.ToString()); } return ValidateOptionsResult.Success; } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using TestProject.Models; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.Configure<TestOption>(Configuration.GetSection("Test")); services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<TestOption>, TestValidation>()); services.AddControllersWithViews(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllerRoute ( name : "default", pattern : "{controller=Home}/{action=Index}/{id?}" ); } ); } #endregion } } |
▶
더 읽기
■ OptionsBuilder<T> 클래스의 Validate 메소드를 사용해 옵션 값을 검증하는 방법을 보여준다. ▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
{ "Test" : { "Key1" : "Key One", "Key2" : 40, "Key3" : 30 }, "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
▶ Models/TestOption.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 스타일 옵션 /// </summary> public class TestOption { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 키 1 - Key1 /// <summary> /// 키 1 /// </summary> [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")] public string Key1 { get; set; } #endregion #region 키 2 - Key2 /// <summary> /// 키 2 /// </summary> [Range(0, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")] public int Key2 { get; set; } #endregion #region 키 3 - Key3 /// <summary> /// 키 3 /// </summary> public int Key3 { get; set; } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestProject.Models; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddOptions<TestOption>() .Bind(Configuration.GetSection("Test")) .ValidateDataAnnotations() .Validate ( testOption => { if(testOption.Key2 != 0) { return testOption.Key3 > testOption.Key2; } return true; }, "Key3 must be > than Key2." ); services.AddControllersWithViews(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllerRoute ( name : "default", pattern : "{controller=Home}/{action=Index}/{id?}" ); } ); } #endregion } } |
▶ Controllers/TestController.cs
더 읽기
■ OptionsBuilderDataAnnotationsExtensions 클래스의 ValidateDataAnnotations 확장 메소드를 사용해 옵션 값을 검증하는 방법을 보여준다. ▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
{ "Test" : { "Key1" : "Key One", "Key2" : 1001, "Key3" : 32 }, "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
▶ Models/TestOption.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 스타일 옵션 /// </summary> public class TestOption { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 키 1 - Key1 /// <summary> /// 키 1 /// </summary> [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")] public string Key1 { get; set; } #endregion #region 키 2 - Key2 /// <summary> /// 키 2 /// </summary> [Range(0, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")] public int Key2 { get; set; } #endregion #region 키 3 - Key3 /// <summary> /// 키 3 /// </summary> public int Key3 { get; set; } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestProject.Models; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddOptions<TestOption>() .Bind(Configuration.GetSection("Test")) .ValidateDataAnnotations(); services.AddControllersWithViews(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllerRoute ( name : "default", pattern : "{controller=Home}/{action=Index}/{id?}" ); } ); } #endregion } } |
▶
더 읽기
■ RangeAttribute 클래스를 사용해 숫자 범위를 설정하는 방법을 보여준다. ▶ Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> [Required] [StringLength(60, MinimumLength = 3)] public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] [Display(Name = "Release Date")] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> [Required] [StringLength(30)] [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")] public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> [DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] [Range(1, 100)] public decimal Price { get; set; } #endregion #region 등급 - Rating /// <summary> /// 등급 /// </summary> [Required] [StringLength(5)] [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")] public string Rating { get; set; } #endregion } } |
■ RangeAttribute 클래스를 사용해 날짜 범위를 설정하는 방법을 보여준다. ▶ Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> [Required] [StringLength(60, MinimumLength = 3)] public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] [Display(Name = "Release Date")] [Range(typeof(DateTime), "2020/01/01", "2020/10/18")] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> [Required] [StringLength(30)] [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")] public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> [DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] [Range(1, 100)] public decimal Price { get; set; } #endregion #region 등급 - Rating /// <summary> /// 등급 /// </summary> [Required] [StringLength(5)] [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")] public string Rating { get; set; } #endregion } } |
■ RegularExpressionAttribute 클래스에서 정규식을 사용하는 방법을 보여준다. ▶ Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> [Required] [StringLength(60, MinimumLength = 3)] public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] [Display(Name = "Release Date")] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> [Required] [StringLength(30)] [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")] public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> [DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] [Range(1, 100)] public decimal Price { get; set; } #endregion #region 등급 - Rating /// <summary> /// 등급 /// </summary> [Required] [StringLength(5)] [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")] public string Rating { get; set; } #endregion } } |
■ ColumnAttribute 클래스의 TypeName 속성을 사용하는 방법을 보여준다. ▶ Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] [Display(Name = "Release Date")] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> [Column(TypeName = "decimal(18, 2)")] public decimal Price { get; set; } #endregion } } |
■ StringLengthAttribute 클래스의 MinimumLength/MaximumLength/ErrorMessage 속성을 사용하는 방법을 보여준다. ▶ TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
■ RequiredAttribute 클래스의 ErrorMessage 속성을 사용하는 방법을 보여준다. ▶ TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
■ DisplayAttribute 클래스의 Name 속성을 사용하는 방법을 보여준다. ▶ TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
■ DataTypeAttribute 클래스의 DataType 속성을 사용하는 방법을 보여준다. ▶ Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
using System; using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> public decimal Price { get; set; } #endregion } } |
■ 태그 헬퍼를 사용해 폼을 구성하는 방법을 보여준다. ▶ Models/TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
using Microsoft.AspNetCore.Mvc; using TestProject.Models; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [HttpGet] public IActionResult Index() { return View(); } #endregion #region 인덱스 페이지 처리하기 - Index(test) /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <param name="test">테스트</param> /// <returns>액션 결과</returns> [HttpPost] public IActionResult Index(TestModel test) { if(ModelState.IsValid) { return View("Completed"); } return View(test); } #endregion #region 완료시 페이지 처리하기 - Completed() /// <summary> /// 완료시 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Completed() { return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
@model TestProject.Models.TestModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>태그 헬퍼를 사용해 폼 구성하기</title> </head> <body> <p>태그 헬퍼를 사용해 폼 구성하기</p> <hr /> <form asp-controller="Test" asp-action="Index" method="post"> <div asp-validation-summary="ModelOnly" /> <p> <label asp-for="Name" /> <input asp-for="Name" /> <span asp-validation-for="Name" /> </p> <p> <label asp-for="Content" /> <input asp-for="Content" /> <span asp-validation-for="Content" /> </p> <p><input type="submit" value="제출" /></p> </form> <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/lib/jquery-validation/jquery.validate.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script> </body> </html> |
▶ Views/Test/Completed.cshtml
|
@{ Layout = null; } <p>모델 기반의 서버측 유효성 검사를 사용해 폼 구성하기</p> <hr /> <script> alert("제출이 완료되었습니다."); </script> |
TestProject.zip
■ 모델 기반의 클라이언트측 유효성 검사를 사용해 폼을 구성하는 방법을 보여준다. ▶ Models/TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
using Microsoft.AspNetCore.Mvc; using TestProject.Models; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [HttpGet] public IActionResult Index() { return View(); } #endregion #region 인덱스 페이지 처리하기 - Index(test) /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <param name="test">테스트</param> /// <returns>액션 결과</returns> [HttpPost] public IActionResult Index(TestModel test) { if(ModelState.IsValid) { return View("Completed"); } return View(test); } #endregion #region 완료시 페이지 처리하기 - Completed() /// <summary> /// 완료시 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Completed() { return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
@model TestProject.Models.TestModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>모델 기반의 클라이언트측 유효성 검사를 사용해 폼 구성하기</title> </head> <body> <p>모델 기반의 클라이언트측 유효성 검사를 사용해 폼 구성하기</p> <hr /> @using(Html.BeginForm()) { <div>@Html.ValidationSummary(false)</div> <p> @Html.LabelFor(model => model.Name) @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </p> <p> @Html.LabelFor(model => model.Content) @Html.TextBoxFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </p> <p><input type="submit" value="제출" /></p> } <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/lib/jquery-validation/jquery.validate.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script> </body> </html> |
▶ Views/Test/Completed.cshtml
더 읽기
■ 모델 기반의 서버측 유효성 검사를 사용해 폼을 구성하는 방법을 보여준다. ▶ Models/TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name = "성명")] [Required(ErrorMessage = "성명을 입력해 주시기 바랍니다.")] [StringLength(25, MinimumLength = 1, ErrorMessage = "성명은 1~25자를 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] [Required(ErrorMessage = "내용을 입력해 주시기 바랍니다.")] [StringLength(255, MinimumLength = 1, ErrorMessage = "내용은 1~244자를 입력해 주시기 바랍니다.")] public string Content { get; set; } #endregion } } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
using Microsoft.AspNetCore.Mvc; using TestProject.Models; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [HttpGet] public IActionResult Index() { return View(); } #endregion #region 인덱스 페이지 처리하기 - Index(test) /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <param name="test">테스트</param> /// <returns>액션 결과</returns> [HttpPost] public IActionResult Index(TestModel test) { if(string.IsNullOrEmpty(test.Name)) { ModelState.AddModelError("Name", "성명을 입력해 주시기 바랍니다."); } if(string.IsNullOrEmpty(test.Content)) { ModelState.AddModelError("Content", "내용을 입력해 주시기 바랍니다."); } if(!ModelState.IsValid) { // @Html.ValidationSummary(true)인 경우 아래 에러 메시지만 표시된다. ModelState.AddModelError("", "에러가 발생했습니다."); } if(ModelState.IsValid) { return View("Completed"); } return View(test); } #endregion #region 완료시 페이지 처리하기 - Completed() /// <summary> /// 완료시 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Completed() { return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
@model TestProject.Models.TestModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>모델 기반의 서버측 유효성 검사를 사용해 폼 구성하기</title> </head> <body> <p>모델 기반의 서버측 유효성 검사를 사용해 폼 구성하기</p> <hr /> @using(Html.BeginForm()) { <div>@Html.ValidationSummary(false)</div> <p> @Html.LabelFor(model => model.Name) @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </p> <p> @Html.LabelFor(model => model.Content) @Html.TextBoxFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </p> <p><input type="submit" value="제출" /></p> } </body> </html> |
▶ Views/Test/Completed.cshtml
더 읽기
■ 강력한 형식의 뷰와 모델 바인딩을 사용해 폼을 구성하는 방법을 보여준다. ▶ Models/TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
using System.ComponentModel.DataAnnotations; namespace TestProject.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Display(Name= "성명")] public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> [Display(Name = "내용")] public string Content { get; set; } #endregion } } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
using Microsoft.AspNetCore.Mvc; using TestProject.Models; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [HttpGet] public IActionResult Index() { return View(); } #endregion #region 인덱스 페이지 처리하기 - Index(test) /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <param name="test">테스트</param> /// <returns>액션 결과</returns> [HttpPost] public IActionResult Index(TestModel test) { return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
@model TestProject.Models.TestModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>강력한 형식의 뷰와 모델 바인딩을 사용해 폼 구성하기</title> </head> <body> <p>강력한 형식의 뷰와 모델 바인딩을 사용해 폼 구성하기</p> <hr /> @using(Html.BeginForm()) { <p>@Html.LabelFor(n => n.Name) @Html.TextBoxFor(n => n.Name)</p> <p>@Html.LabelFor(c => c.Content) @Html.TextBoxFor(c => c.Content)</p> <p><input type="submit" value="제출" /></p> } </body> </html> |
TestProject.zip
■ 헬퍼 메소드를 사용해 폼을 구성하는 방법을 보여준다. ▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
using Microsoft.AspNetCore.Mvc; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> [HttpGet] public IActionResult Index() { return View(); } #endregion #region 인덱스 페이지 처리하기 - Index(name, content) /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <param name="name">성명</param> /// <param name="content">내용</param> /// <returns>액션 결과</returns> [HttpPost] public IActionResult Index(string name, string content) { ViewBag.Name = name; ViewBag.Content = content; return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>헬퍼 메소드를 사용해 폼 구성하기</title> <script> function CheckForm() { var name = document.getElementById("name"); var content = document.getElementById("content"); if(name.value.length < 1 || content.value.length < 1) { window.alert("성명과 내용을 입력해 주시기 바랍니다."); name.focus(); name.select(); return false; } return true; } </script> </head> <body> <p>헬퍼 메소드를 사용해 폼 구성하기</p> <hr /> @using(Html.BeginForm("Index", "Test", new { }, FormMethod.Post, false, new { @class = "FormStyle", data_ng_test = "test", onsubmit = "return CheckForm();" })) { <p><text>성명 </text> @Html.TextBox("name")</p> <p><text>내용 </text> @Html.TextBox("content")</p> <p><input type="submit" value="제출" /></p> } @if(ViewBag.Name != null) { <hr /> <p>성명 : @ViewBag.Name</p> <p>내용 : @ViewBag.Content</p> } </body> </html> |
TestProject.zip
■ 순수 HTML 태그를 사용해 폼을 구성하는 방법을 보여준다. ▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
using Microsoft.AspNetCore.Mvc; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Index() { return View(); } #endregion #region 완료시 페이지 처리하기 - Completed(name, content) /// <summary> /// 완료시 페이지 처리하기 /// </summary> /// <param name="name">성명</param> /// <param name="content">내용</param> /// <returns>액션 결과</returns> public IActionResult Completed(string name, string content) { ViewBag.Name = name; ViewBag.Content = content; return View(); } #endregion } } |
▶ Views/Test/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>순수 HTML 태그를 사용해 폼 구성하기</title> <script> function CheckForm() { var name = document.getElementById("name" ); var content = document.getElementById("content"); if (name.value.length < 1 || content.value.length < 1) { window.alert("성명과 내용을 입력해 주시기 바랍니다."); name.focus(); name.select(); return false; } return true; } </script> </head> <body> <p>순수 HTML 태그를 사용해 폼 구성하기</p> <hr /> <form action="/Test/Completed" method="post" onsubmit="return CheckForm();"> <p>성명 <input type="text" name="name" id="name" value="" /></p> <p>내용 <input type="text" name="content" id="content" value="" /></p> <p><input type="submit" value="제출" /></p> </form> </body> </html> |
▶ Views/Test/Completed.cshtml
|
@{ Layout = null; } <p>순수 HTML 태그를 사용해 폼 구성하기</p> <hr /> <p>성명 : @ViewBag.Name</p> <p>내용 : @ViewBag.Content</p> |
TestProject.zip
■ CustomValidator 클래스를 사용해 항목을 1개 이상 체크하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CustomValidator 클래스 : 항목을 1개 이상 체크하기</title> <script type="text/javascript"> function CheckValue(sender, e) { var checkBoxList = 'favoriteCheckBoxList'; var options = document.getElementById(checkBoxList).getElementsByTagName('input'); var ischecked = false; e.IsValid = false; for(i = 0; i < options.length; i++) { var option = options[i]; if(option.type == "checkbox") { if(option.checked) { ischecked = true; e.IsValid = true; } } } } </script> </head> <body> <form id="form" runat="server"> <div> <asp:CheckBoxList ID="favoriteCheckBoxList" runat="server" ValidationGroup="CheckGroup"> <asp:ListItem Value="0">ASP.NET</asp:ListItem> <asp:ListItem Value="1">Bootstrap</asp:ListItem> <asp:ListItem Value="2">C#</asp:ListItem> <asp:ListItem Value="3">Dapper</asp:ListItem> </asp:CheckBoxList> <asp:CustomValidator ID="favoriteCustomValidator" runat="server" ErrorMessage="반드시 하나 이상을 체크하세요." ClientValidationFunction="CheckValue" ValidationGroup="CheckGroup" Display="None" /> <asp:ValidationSummary runat="server" DisplayMode="List" ShowSummary="false" ShowMessageBox="true" ValidationGroup="CheckGroup" /> <asp:Button ID="submitButton" runat="server" ValidationGroup="CheckGroup" Text="제출" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ CustomValidator 클래스를 사용해 약관 동의하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CustomValidator 클래스 : 약관 동의하기</title> <script> function ValidationConfirmCheckBox(sender, e) { if(document.getElementById("<%= confirmCheckBox.ClientID %>").checked == true) { e.IsValid = true; } else { e.IsValid = false; } } </script> </head> <body> <form id="form" runat="server"> <div> <label for="optGender"> <asp:Literal ID="Literal1" runat="server">이용 약관</asp:Literal>: </label> <div> <p>회원 이용 약관에 동의하셔야 회원가입을 하실 수 있습니다.</p> <asp:TextBox ID="agreementTextBox" runat="server" Style="font-size:9pt;" Width="100%" Height="80px" TextMode="MultiLine"> </asp:TextBox> <div> <label> <asp:CheckBox ID="confirmCheckBox" runat="server" Checked="false" /> <asp:Literal ID="agreeLicenseLiteral" runat="server"> 위 약관에 동의합니다.(Accept the license) </asp:Literal> </label> </div> <asp:CustomValidator ID="confirmCustomValidator" runat="server" ErrorMessage="약관에 동의하셔야 합니다." ClientValidationFunction="ValidationConfirmCheckBox"> </asp:CustomValidator> <asp:ValidationSummary ID="validationSummary" runat="server" ShowSummary="false" ShowMessageBox="true" /> <div> <asp:Button ID="submitButton" runat="server" Text="가입하기" /> </div> </div> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ ValidationSummary 클래스를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ValidationSummary 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <h3>유효성 검사 요약 컨트롤</h3> 아이디 : <asp:TextBox ID="userIDTextBox" runat="server" /> <asp:RequiredFieldValidator ID="userIDRequiredFieldValidator" runat="server" ControlToValidate="userIDTextBox" Display="None" ErrorMessage="아이디를 입력해주시 바랍니다."> </asp:RequiredFieldValidator> <br /> 암호 : <asp:TextBox ID="passwordTextBox" runat="server" TextMode="Password"> </asp:TextBox> <asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server" ControlToValidate="passwordTextBox" Display="None" ErrorMessage="암호를 입력해주시기 바랍니다."> </asp:RequiredFieldValidator> <hr /> <asp:LinkButton ID="loginLinkButton" runat="server"> 로그인 </asp:LinkButton> <br /> <asp:ValidationSummary ID="validationSummary" runat="server" ShowMessageBox="true" ShowSummary="true" DisplayMode="BulletList" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ Validation 클래스의 Errors 첨부 속성을 바인딩하는 방법을 보여준다. ▶ 예제 코드 (XAML)
|
Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)/ErrorContent}" /> Content="{Binding ElementName=stackPanel, Path=(Validation.Errors)[0].ErrorContent}" |
※ Path=(Validation.Errors)/ErrorContent과 (Validation.Errors)[0].ErrorContent는 동일하다.
■ RequiredFieldValidator 클래스의 InitialValue 속성을 사용해 기본값을 설정하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>RequiredFieldValidator 클래스 : InitialValue 속성을 사용해 기본값 설정하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:DropDownList ID="dropDownList" runat="server" /> <asp:Button ID="selectButton" runat="server" Text="선택" OnClick="selectButton_Click" /> <hr /> <asp:Label ID="resultLabel" runat="server" Text="" /> <asp:RequiredFieldValidator ID="requiredFieldValidator" runat="server" ControlToValidate="dropDownList" InitialValue="-1" Display="None" ErrorMessage="목록에서 항목을 선택해 주시기 바랍니다."> </asp:RequiredFieldValidator> <asp:ValidationSummary ID="validationSummary" runat="server" ShowMessageBox="true" ShowSummary="false" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
using System; using System.Web.UI; using System.Web.UI.WebControls; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { this.dropDownList.Items.Add(new ListItem("[미정]", "-1")); for(int i = 0; i < 10; i++) { ListItem listItem = new ListItem(i.ToString(), i.ToString()); this.dropDownList.Items.Add(listItem); } } } #endregion #region 선택 버튼 클릭시 처리하기 - selectButton_Click(sender, e) /// <summary> /// 선택 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void selectButton_Click(object sender, EventArgs e) { this.resultLabel.Text = this.dropDownList.SelectedValue; } #endregion } } |
TestProject.zip