Japanese text validation with regex

 Japanese text validation with regex

1. Japanese double byte, full and half width character validation and sample code for angular.
2. Creating custom validation in angular reactive form




export const regHiragana = /[\u3040-\u309F]+/g;
export const regKanji = /[\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A]+/g;
export const regKatakanFull = /[\u30A0-\u30FF]+/g;
export const regKatakanHalf = /[\uFF5F-\uFF9F]+/g;
export const regAlphaNumeric = /[\w\d]+/g
export const regAddr01N = /[\uFF5F-\uFF9F\w\d\u0020]+/g;


function isJapChar ($str: string, regex: RegExp)
{
  let res = $str.match(regex);
  if(res != null){
    if (res[0] == $str) {
      return true;
    }
  }
  return false;
}


export function katakanaValidate(control: AbstractControl):
{ [key: string] : any} | null | void {
  const vals : string = control.value;
  let pattern = regKatakanFull;

  if(isJapChar(vals, pattern )){
 
    return null;
  }    
  return { 'katakanaValidate': true};
}

export function alphaNumericValidate(control: AbstractControl):
{ [key: string] : any} | null | void {
  const vals : string = control.value;
  let pattern = regAlphaNumeric;
  if((vals == '') || isJapChar(vals, pattern )){
    return null;
  }    
  return { 'alphaNumericValidate': true};
}

export function doubleByteValidate(control: AbstractControl):
{ [key: string] : any} | null | void {
  const vals : string = control.value;


  if((vals == '')
|| isJapChar(vals, regHiragana )
|| isJapChar(vals, regKanji )
|| isJapChar(vals, regKatakanFull )
|| isJapChar(vals, regKatakanHalf )){
    return null;
  }    
  return { 'doubleByteValidate': true};
}


2. validation rule in angular
nickname: ['', [Validators.required, doubleByteValidate, Validators.maxLength(20)]],

Share this

Related Posts

Previous
Next Post »