| 제목 | 폼 검증 에러메시지 조사 처리하기 | ||
|---|---|---|---|
| 글쓴이 | 천재작곡가 | 작성시각 | 2016/05/29 04:12:11 | 
| 
                         | 
                |||
| 
                         안녕하세요 반갑습니다. 현재 HyeongJoo Kwon 님이 번역해서 올려주신 form_validation_lang.php 파일을 보면 {field}(은)는 필수입니다. 이런형식으로 되어있습니다. 번역하시느라 매우 고생이많으셨습니다! 저는 개인적으로 이 번역투의 말을 좀더 매끄럽게 해보고자, (은)는 형식이 아닌 앞글자의 종성 여부를 판단해서 조사를 치환하도록 만들어 봤습니다. 
 @ application/libraries/MY_Form_validation.php 
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Form Validation Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Validation
 * @author		EllisLab Dev Team
 * @link		https://codeigniter.com/user_guide/libraries/form_validation.html
 */
class MY_Form_validation extends CI_Form_validation {
	
	function __construct() {
		parent::__construct();
	}
	
	public function error_string($prefix = '', $suffix = '')
	{
		// No errors, validation passes!
		if (count($this->_error_array) === 0)
		{
			return '';
		}
		if ($prefix === '')
		{
			$prefix = $this->_error_prefix;
		}
		if ($suffix === '')
		{
			$suffix = $this->_error_suffix;
		}
		// Generate the error string
		$str = '';
		foreach ($this->_error_array as $val)
		{
			if ($val !== '')
			{
				$str .= $prefix.$val.$suffix."\n";
			}
		}
		// return $str;
		return $this->josa_conv($str);
	}
	
	/**
	 * 문장에서 조사를 적절하게 변환시킵니다.
	 */
	public static function josa_conv($str)
    {
        $josa = '이가은는을를과와';
		
		 return preg_replace_callback("/(.)\\{([{$josa}])\\}/u",
        	function($matches) use($josa) {
        		
				// 조사 바로 앞 한글자
        		$lastChar = $matches[1];
        		$postpositionMatched = $matches[2];
				
				 $arrPostposition = array(
		            'N' => $postpositionMatched,
		            'Y' => $postpositionMatched
		        );
		        $pos = mb_strpos($josa, $postpositionMatched);
		        if ($pos % 2 != 0) {
		            $arrPostposition['Y'] = mb_substr($josa, $pos-1, 1);
		        } else {
		            $arrPostposition['N'] = mb_substr($josa, $pos+1, 1);
		        }
				
				// 기본값 : 종성있음
				$lastCharStatus = 'Y';
 
		        // 2바이트 이상 유니코드 문자
		        if (strlen($lastChar) > 1) {
					
					switch (strlen($lastChar)) {
			            case 1:
			                $lastchar_code = ord($lastChar);
			                break;
			            case 2:
			                $lastchar_code = ((ord($lastChar[0]) & 0x1F) << 6) | (ord($lastChar[1]) & 0x3F);
			                break;
			            case 3:
			                $lastchar_code = ((ord($lastChar[0]) & 0x0F) << 12) | ((ord($lastChar[1]) & 0x3F) << 6) | (ord($lastChar[2]) & 0x3F);
			                break;
			            case 4:
			                $lastchar_code = ((ord($lastChar[0]) & 0x07) << 18) | ((ord($lastChar[1]) & 0x3F) << 12) | ((ord($lastChar[2]) & 0x3F) << 6) | (ord($lastChar[3]) & 0x3F);
			                break;
			            default:
			                $lastchar_code = $lastChar;
			        }
					
		            $code = $lastchar_code - 44032;
		 
		            // 한글일 경우 (가=0, 힣=11171)
		            if ($code > -1 && $code < 11172) {
		                // 초성
		                //$code / 588
		                // 중성
		                //$code % 588 / 28
		                // 종성
		                if ($code % 28 == 0) $lastCharStatus = 'N';
		            }
		        // 1바이트 ASCII
		        } else {
		            // 숫자중 2(이),4(사),5(오),9(구)는 종성이 없음
		            if (strpos('2459', $lastChar) > -1) {
		                $lastCharStatus = 'N';
		            }
		        }				
            	return $lastChar.$arrPostposition[$lastCharStatus];
				
        	}, $str 
		);
    }
}
@ system/language/korean/form_validation_lang.php <?php /** * System messages translation for CodeIgniter(tm) * * @author CodeIgniter community * @author HyeongJoo Kwon * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['form_validation_required'] = '{field}{은} 필수입니다.'; $lang['form_validation_isset'] = '{field}{은} 필수입니다.'; $lang['form_validation_valid_email'] = '{field}{이} 유효한 이메일 주소 형식이 아닙니다.'; $lang['form_validation_valid_emails'] = '{field}{이} 하나 이상의 이메일 주소가 유효한 형식이 아닙니다.'; $lang['form_validation_valid_url'] = '{field}{이} 유효한 URL이 아닙니다.'; $lang['form_validation_valid_ip'] = '{field}{이} 유효한 IP가 아닙니다.'; $lang['form_validation_min_length'] = '{field}{은} 최소 {param}자 이상이어야 합니다.'; $lang['form_validation_max_length'] = '{field}{은} 최대 {param}자 이하여야 합니다.'; $lang['form_validation_exact_length'] = '{field}{은} 정확히 {param}자 이어야 합니다.'; $lang['form_validation_alpha'] = '{field}{은} 영문이어야 합니다.'; $lang['form_validation_alpha_numeric'] = '{field}{은} 영문-숫자 조합이어야 합니다.'; $lang['form_validation_alpha_numeric_spaces'] = '{field}{은} 영문-숫자-공백 조합이어야 합니다.'; $lang['form_validation_alpha_dash'] = '{field}{은} 영문-\'-\'-\'_\' 조합이어야 합니다.'; $lang['form_validation_numeric'] = '{field}{은} 숫자이어야 합니다.'; $lang['form_validation_is_numeric'] = '{field}{은} 반드시 숫자를 포함하여야 합니다.'; $lang['form_validation_integer'] = '{field}{은} 반드시 정수여야 합니다.'; $lang['form_validation_regex_match'] = '{field}{은} 유효한 입력값이 아닙니다.'; $lang['form_validation_matches'] = '{field}{은} {param}{와} 일치하지 않습니다.'; $lang['form_validation_differs'] = '{field}{은} {param}{와} 일치하지 않아야 합니다.'; $lang['form_validation_is_unique'] = '{field}{은} 고윳값이 아닙니다.'; $lang['form_validation_is_natural'] = '{field}{은} 반드시 수를 포함하여야 합니다.'; $lang['form_validation_is_natural_no_zero'] = '{field}{은} 반드시 숫자를 포함하고, 0보다 커야 합니다.'; $lang['form_validation_decimal'] = '{field}{은} 반드시 소수여야 합니다.'; $lang['form_validation_less_than'] = '{field}{은} {param}보다 작아야 합니다.'; $lang['form_validation_less_than_equal_to'] = '{field}{은} {param}보다 작거나 같아야 합니다.'; $lang['form_validation_greater_than'] = '{field}{은} {param}보다 커야 합니다.'; $lang['form_validation_greater_than_equal_to'] = '{field}{은} {param}보다 크거나 같아야 합니다.'; $lang['form_validation_error_message_not_set'] = '{field} 필드의 에러메시지가 설정되어있지 않습니다.'; $lang['form_validation_in_list'] = '{field} 필드는 반드시 다음 중 하나와 일치해야 합니다 : {param}'; 
 원리는 조사부분을 {} 이걸로 감싼뒤, 에러메시지를 보여주기전에 {조사} 를 검사하여 조사를 치환시키는 것입니다. 로그인아이디{은} 필수입니다. 와 같은 글이 작성된다면 로그인아이디는 필수입니다. 이런형식으로 변환이 됩니다. 
 소스는 http://bloodguy.tistory.com/entry/PHP-한글-종성유무에-맞는-조사은는이가-변환 이곳을 참조하였습니다.  | 
                |||
| 태그 | 폼검증,조사,종성 | ||
| 관련링크 | 
                            http://bloodguy.tistory.com/entry/PHP-한글-종성유무에-맞는-조사은는이가-변환 | 
                    ||
| 다음글 | 위젯 라이브러리(?) 입니다. (1) | ||
| 이전글 | PHP MongoDB 드라이버 이용시 Object ID... (1) | ||
| 
                             
                                한대승(불의회상)
                                /
                                2016/05/30 13:41:13 /
                                추천
                                0
                             
                             | 
                    
| 
                             
                                유마
                                /
                                2016/08/20 17:45:38 /
                                추천
                                0
                             
                            
                                해보니까, error() 함수도 오버라이딩해야 되네요. error_string() 함수는 validation_error() 함수에만 적용 되고, form_error() 함수는 error() 함수를 사용하네요.
                             
                         | 
                    
| 
                             
                                너그
                                /
                                2016/12/15 13:08:17 /
                                추천
                                0
                             
                            와.. 여지것 "아이디" 누락되었습니다로 경고메세지 나오게했는데.. 이제야 조사를 붙일수 있게되었네요 감사합니다~  | 
                    
| 
                             
                                미나리나물
                                /
                                2017/08/12 00:20:31 /
                                추천
                                0
                             
                            이 라이브러리는 정확하게 어떻게 사용해야 하나요? 제 ci에는 {field} 대신 %s 로 되어 있어서 오류가 발생합니다.  | 
                    
| 
                             
                                변종원(웅파)
                                /
                                2017/08/12 21:38:14 /
                                추천
                                0
                             
                            
                                미나리나물님 ci버전은요?
                             
                         | 
                    
| 
                             
                                미나리나물
                                /
                                2017/08/14 13:13:40 /
                                추천
                                0
                             
                            
                                CI 버전은 2.1 입니다.
                             
                         | 
                    
| 
                             
                                변종원(웅파)
                                /
                                2017/08/14 17:31:17 /
                                추천
                                0
                             
                            미나리나물/ 폼검증을 확장했고 그에 따라 에러메세지 파일도 변경을 하신 것 같네요. 위 소스를 메세지파일에 넣어주셔야합니다.  | 
                    
이제 올바른 메시지를 사용하는게 가능 하겠네요.
수고 하셨습니다.