2016-12-08 36 views
0

我有一個註冊表單,我正在使用第三方庫來驗證輸入。這個庫爲驗證提供了非常好的和很酷的效果,但我需要進行另一次驗證以確保密碼和確認密碼匹配。我怎麼能通過jQuery來做到這一點?這裏是我的代碼:將jQuery中的兩個驗證合併爲密碼字段

<div class="form-group"> 
    <label>Password</label> 
    <input type="password" class="form-control" name="password" /> 
</div> 
<div class="form-group"> 
    <label>Retype Password</label> 
    <input type="password" class="form-control" name="password2" /> 
</div> 

和jQuery部分:

$('#registrationForm').formValidation({ 
    framework: 'bootstrap', 
    fields: { 
     password: { 
      validators: { 
       notEmpty: { 
        message: 'The password is required' 
       } 
      } 
     }, 
     password2: { 
      validators: { 
       notEmpty: { 
        message: 'Password conformation is required' 
       }, 
       equalTo: { 
        field: 'password', 
        message: 'The password cannot be the same as username' 
       } 
      } 
     } 
    } 
}); 

我應該把問號代替,以解決我的問題?或者,我可能完全錯誤的語法?

+0

jQuery在哪裏?你在那裏有一個嵌套的對象文字。 –

+0

你使用Validate.js嗎? –

+0

不,我正在使用formvalidation.io – Amir

回答

1

Working Fiddle

HTML:

<form id="formCheckPassword"> 

    <div class="form-group"> 
    <label>Password</label> 
    <input type="password" class="form-control" name="password" id="password" /> 
    </div> 
    <div class="form-group"> 
    <label>Retype Password</label> 
    <input type="password" class="form-control" name="cfmPassword" id="cfmPassword" /> 
    </div> 
    <input type="submit" value="submit" /> 
</form> 

和jQuery規則:

$("#formCheckPassword").validate({ 
    rules: { 
    password: { 
     required: true, 
     minlength: 6, 
     maxlength: 10, 

    }, 

    cfmPassword: { 
     equalTo: "#password", 
     minlength: 6, 
     maxlength: 10 
    } 


    }, 
    messages: { 
    password: { 
     required: "the password is required" 

    } 
    } 

}); 

根據要求更新:

$('#RegistrationForm').formValidation({ 
    framework: 'bootstrap', 
    fields: { 
     password: { 
      validators: { 
       identical: { 
        field: 'confirmPassword', 
        message: 'The password and its confirm are not the same' 
       } 
      } 
     }, 
     confirmPassword: { 
      validators: { 
       identical: { 
        field: 'password', 
        message: 'The password and its confirm are not the same' 
       } 
      } 
     } 
    } 
}); 
+0

謝謝Shree。你能否根據這段代碼重寫你的代碼? $( '#registrationForm')formValidation({ 框架: '引導', 字段:{ PW:{ 驗證:{ notEmpty:{ 消息: '時需要輸入密碼' } } }, PW2:{ 驗證:{ notEmpty:{ 信息: '構象需要' } } } } }); – Amir

+0

查看驗證更新。 –

+0

完美!謝謝! – Amir

0

我沒有看到它在這種語法中工作。如果您想通過jQuery來做到這一點(如你所提到的),你可以簡單地檢查值:

var password1 = $('input[name=password]').val(); 
var password2 = $('input[name=password2]').val(); 
var match = password1 == password2