2012-05-22 5 views
4

node.js를 사용하고 표현형 (2.5.9)을 표현식으로 사용하십시오.익스프레스 양식의 유효성 검사 오류 후 양식 필드를 다시 채우는 방법은 무엇입니까?

양식 필드에 제출 된 값을 어떻게 다시 채워야합니까?

나는 getpost 경로가 있습니다. 양식이 게시 될 때 유효성 검사 오류가 발생하면 사용자를 get로 다시 리디렉션합니다. 문제는 다시 채워진 지역이 표시되지 않는다는 것입니다 (autoLocals : true가 있으므로 리디렉션하고 있기 때문에 가정합니다) res ,

가 어떻게 너희들이 다시 채 웁니다 않고 응용 프로그램의 흐름은 무엇입니까). 리셋 당신은 res.send 대신 res.redirect하고 다시 전체를 설정합니까? 그것은 반복적 인 것처럼 보인다. 여기

내 포스트 경로의 예 : 그것은 가장 좋은 방법은,하지만 내가 검증 실패가있을 때, 나는 종종 제어를 전달하여 (난 그냥 뷰를 다시 렌더링 리디렉션하지 않는 경우

app.post(

    '/projects/:id' 

    , form(field("title").required("title", "Title is required) 
    , function (req, res){ 

    if (!req.form.isValid){ 
    res.redirect('/project/'+req.params.id+'/edit'); 
    } 
    else{ 
    // save to db 
    } 

}); 

답변

2

확실하지 않음 'get'콜백으로). 비슷한 모양 :

function loadProject(req,res, id){ /* fetch or create logic, storing as req.model or req.project */} 

function editProject(req,res){ /* render logic */ } 

function saveProject(req,res){ 
    if(!req.form.isValid){ 
     editProject(req,res); 
    }else{ 
     saveToDb(req.project); 
     res.redirect('/project'+req.project.id+'/edit'); 
    } 
} 

app.param('id', loadProject); 
app.get('/projects/:id/edit', editProject); 
app.post('/projects/:id', saveProject); 
+1

좋습니다. 그래서 내 문제는 리디렉션을하고 리셋을했다는 사실이었습니다. 필자가 배운 것은 '프로젝트 [제목]'과 같은 "다중 레벨"이름/경로를 가진 필드를 다시 채울 때 별도의 문제가 있다는 것입니다 (일반적으로 몽구스를 사용할 때 그렇듯이). 그들은 다시 채우지 않는다. 익스프레스 양식을 좀 더 파고 들어가서 해결할 수있는 것이 있는지 확인하십시오. – k00k

1

나는 비슷한 문제를 최근에 해결해야했고 두 개의 노드 모듈 인 validator와 flashify를 사용했다.

div.control-group 
     label.control-label Description 
     div.controls 
      textarea(name='eventForm[desc]', id='desc', rows='3').input-xxlarge= eventForm.desc 

     div.control-group 
     label.control-label Tag 
     div.controls 
      select(id='tag', name='eventForm[tag]') 
      tags = ['Medjugorje', 'Kibeho', 'Lourdes', 'Fatima'] 
      for tag in tags 
       option(selected=eventForm.tag == tag)= tag 

공지 사항 양식 필드의 이름 지정 규칙을 다음과 같이

폼보기에서 내 양식 필드를 구성했습니다. 그럼 내 설정 파일에 정말 때 폼 처음로드 단지 자리 표시 자입니다 하나 개의 전역 변수를 설정합니다

//locals 
app.locals.eventForm = []; // placeholder for event form repopulation 

검증 로직이 내 라우터 파일에 있으며 다음과 같습니다

app.post('/posts', function(req, res){ 
    var formData = req.body.eventForm; 
    var Post = models.events; 
    var post = new Post(); 

    post.text   = formData.desc; 
    post.tag   = formData.tag; 

    // run validations before saving 
    var v = new Validator(); 
    var isPostValid = true; 

    // custom error catcher for validator, which uses flashify 
    v.error = function(msg) { 
    res.flash('error', msg); 
    isPostValid = false; 
    } 

    v.check(post.text, "Description field cannot be empty").notEmpty(); 
    v.check(post.tag, "Tag field cannot be empty").notEmpty(); 

은 그 때 나는 오류가 확인, 그렇다면보기로 다시 폼 데이터를 전달 :이 evenForm 데이터가 다시 기본 값을 다시 채 웁니다 뷰에 전달되는

// reject it 
    res.render('Event.jade', {page: req.session.page, eventForm: formData}); 

공지 사항.

최종 단계는 flashify 구성 요소를 폼보기에 포함시키는 것입니다.

div(style='margin-top: 60px').container-fluid 
     include flashify 

flashify보기의 코드는 다음과 같습니다

router.route('/posts/new') 
.get(function(req, res) { 
res.render('posts/new', new Post({})); 
}); 

두 번째를 : 나는 당신이 검증 후 양식 필드를 다시 채울 expressjs4.0 함께 일하고

if (flash.error != undefined) 
div.container 
    div.alert.alert-error 
     b Oops! 
     button(type='button', data-dismiss='alert').close × 
     ul 
      each error in flash.error 
       li= error 
if (flash.success != undefined) 
div.container 
    div.alert.alert-success 
     b Success! 
     button(type='button', data-dismiss='alert').close × 
     ul 
      each success in flash.success 
       li= success 
4

아래의 res.render에 인수가 있으면 뷰에 일부 변수가 설정됩니다.

... 
<input type="text" name="title" value="<%- post.title %>"> 
<textarea name="article"><%- post.article %></textarea> 
... 

이 양식을 제출

, 그것은과 같이 라우터에 의해 체포해야합니다 :

router.route('/posts') 
    .post(function(req, res) { 
    var post = new Post(req.body) 
     post.save(function(err) { 
     if (err) { 
     res.locals.errors = err.errors; 
     res.locals.post = post; 
     return res.render('posts/new'); 
     } 
     return res.redirect('/posts'); 
    }); 
    ... 
}) 

이 다음과 같이 내보기에

res.render('posts/new', new Post({})); 

나는 다음 내 양식 필드를 설정 코드 줄로보기의 양식 필드를 재설정합니다.

res.locals.post = post; 

누군가가 유용하다고 생각하길 바랍니다.)

관련 문제