Scalatra에 대한 요청 매개변수를 검증하고 매핑하는 라이브러리입니다.
공지: 이 프로젝트는 Scalatra에 병합되었기 때문에 더 이상 유지 관리되지 않습니다! 자세한 내용은 Scalatra 설명서를 참조하세요.
먼저 scalatra-forms를 사용하려면 build.sbt에 다음 종속성을 추가하세요.
libraryDependencies += " io.github.gitbucket " %% " scalatra-forms " % " 1.1.0 " 다음으로 Scalatra 애플리케이션의 Bootstrap에 ValidationJavaScriptProvider 추가합니다.
import io . github . gitbucket . scalatra . forms . _
class ScalatraBootstrap extends LifeCycle {
override def init ( context : ServletContext ) {
...
context.mount( new ValidationJavaScriptProvider , " /assets/js/* " )
...
}
}이제 scalatra-forms가 준비되었습니다.
양식 매핑을 정의합니다. Play2와 비슷하지만 scalatra-forms가 더 유연합니다.
import io . github . gitbucket . scalatra . forms . _
case class RegisterForm ( name : String , description : String )
val form = mapping(
" name " -> text(required, maxlength( 40 )),
" description " -> text()
)( RegisterForm .apply) 다음으로 ScalatraServlet(또는 ScalatraFilter)을 확장하는 서블릿(또는 필터)을 만듭니다. 또한 FormSupport 또는 ClientSideValidationFormSupport 에도 혼합되어 있습니다. 매핑된 요청 매개변수인 개체가 작업의 인수로 전달됩니다.
class RegisterServlet extends ScalatraServlet with ClientSideValidationFormSupport {
post( " /register " , form) { form : RegisterForm =>
...
}
}HTML에서는 아래 두 가지 작업을 수행해야 합니다.
<script> 추가하세요.ValidationJavaScriptProvider 에서 제공하는 클라이언트 측 유효성 검사에 도움이 되는 <script> 추가하여 유효성 검사.js를 가져옵니다.<form> 에 validation="true" 추가하세요. scalatra-forms는 제출 이벤트 리스너를 등록하여 양식 내용을 검증합니다. 이 리스너는 모든 양식 내용을 FORM_ACTION/validate 에 게시합니다. 이 작업은 양식 내용의 유효성을 검사하기 위해 scalatra-forms에 자동으로 등록됩니다. 유효성 검사 결과를 JSON으로 반환합니다.
클라이언트 측에서 scalatra-forms는 오류 메시지를 span#error-FIELD_NAME 에 넣습니다.
< script src = " http://code.jquery.com/jquery-2.0.3.min.js " ></ script >
< script src = " /assets/js/validation.js " ></ script >
...
< form method = " POST " action = " /register " validation = " true " >
Name : < input type = " name " type = " text " >
< span class = " error " id = " error-name " ></ span >
< br />
Description : < input type = " description " type = " text " >
< span class = " error " id = " error-description " ></ span >
< br />
< input type = " submit " value = " Register " />
</ form > 사용자 정의 Constraint 생성할 수 있습니다.
def identifier : Constraint = new Constraint (){
override def validate ( name : String , value : String ) : Option [ String ] =
if ( ! value.matches( " ^[a-zA-Z0-9 \ -_]+$ " )){
Some ( s " ${name} contains invalid character. " )
} else {
None
}
}
val form = mapping(
" name " -> text(required, identifier),
" description " -> text()
)( RegisterForm .apply) validate(String, String, Map[String, String]) 재정의하여 다중 필드 유효성 검사기를 만들 수도 있습니다. params 통해 다른 필드 값을 조회할 수 있습니다.
다중 필드 유효성 검사기를 만드는 다른 방법은 매핑 verifying 호출하는 것입니다. 매핑된 케이스 클래스의 유효성을 검사하는 기능을 제공할 수 있습니다. 이 함수는 매핑된 값을 가져와서 오류가 포함된 Seq[(String, String)] 또는 Nil 반환합니다.
val form = mapping(
" reason " -> number(required),
" description " -> optional(text)
)( ReasonForm .apply).verifying { value =>
if (value.reason == 4 && value.descripsion){
Seq ( " description " -> " If reason is 'Other' then description is required. " )
} else {
Nil
}
} Ajax 작업의 경우 get 또는 post 대신 ajaxGet 또는 ajaxPost 사용하세요. ajaxGet 또는 ajaxPost 로 정의된 작업은 유효성 검사 결과를 JSON 응답으로 반환합니다.
class RegisterServlet extends ScalatraServlet with ClientSideValidationFormSupport {
ajaxPost( " /register " , form) { form : RegisterForm =>
...
}
} 클라이언트 측에서는 displayErrors() 사용하여 오류 메시지를 렌더링할 수 있습니다.
$ ( '#register' ) . click ( function ( e ) {
$ . ajax ( $ ( this ) . attr ( 'action' ) , {
type : 'POST' ,
data : {
name : $ ( '#name' ) . val ( ) ,
description : $ ( '#description' ) . val ( )
}
} )
. done ( function ( data ) {
$ ( '#result' ) . text ( 'Registered!' ) ;
} )
. fail ( function ( data , status ) {
displayErrors ( $ . parseJSON ( data . responseText ) ) ;
} ) ;
} ) ; io.github.gitbucket 으로 변경합니다.put() , delete() , ajaxPut() 및 ajaxDelete() 를 ClientSidevalidationFormSupport 에 추가합니다.long 값 유형에 대한 버그 수정.%s )을 사용할 수 있습니다.dummy() 버그를 수정했습니다.long 값 유형을 추가합니다.list 버그를 수정합니다.dummy 값 유형을 추가합니다.MappingValueType 에 대한 verifying() 수정하고 대신 MappingConstraint 제거합니다.length 제한을 추가합니다.MappingValueType 으로 변환된 객체의 유효성을 검사하려면 MappingConstraint 추가하세요.SingleValueType 에 대한 list() 매핑을 추가합니다.ValidationJavaScriptProvider 유효성 검사.js에 대한 Content-Type 헤더를 추가합니다.oneOf() 제약 조건을 추가합니다.number() 및 double() 에 대한 오류 메시지를 검색하도록 수정되었습니다.double() 및 date() 매핑을 추가합니다.ValidationJavaScriptProvoider 추가합니다.list() 매핑을 추가합니다.Constraint 에 validate(String, String, Map[String, String]) 추가합니다. 단일 필드 유효성 검사에서 다른 매개 변수에 액세스할 수 있습니다.MappingValueType 에 verify() 추가합니다.