bootstrap表單驗證插件 經驗記錄 與RSA加密事件配合修改

\繼大概只有自己能懂的乾貨 註冊表單密碼RSA加密 再續寫表單驗證。

因爲項目用的是bootstrap,所以就將就到底,直接用bootstrapvalidate 插件了。
兩個插件文件引進來先,可以在官網下載
1. bootstrapValidator.min.css
2. bootstrapValidator.min.js

隨便找個頁面吧,修改密碼的頁面,只有三個密碼框,但是數據都要加密。直接看代碼就知道怎麼用了,查查插件的api就知道怎麼用了。

<script type="text/javascript">
    $(function () {
        $('#UpdatePasswordForm').bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                Password: {
                    validators: {
                        notEmpty: {
                            message: '請輸入當前密碼。'
                        },
                        regexp: {
                            regexp: /^((?=.*[a-z])(?=.*[A-Z])(?=.*\W).{8,})$/,
                            message: '原密碼格式錯誤'
                        }
                    }
                },
                NewPassword: {
                    validators: {
                        notEmpty: {
                            message: '請輸入新密碼。'
                        },
                        regexp: {
                            regexp: /^((?=.*[a-z])(?=.*[A-Z])(?=.*\W).{8,})$/,
                           message: '密碼格式不符'
                        }
                    }
                },
                ConfirmPassword: {
                    validators: {
                        notEmpty: {
                            message: '請輸入確認密碼。'
                        },
                        identical: {
                            field: 'NewPassword',
                            message: '兩次輸入的密碼不一致。'
                        }
                    }
                }
            }//fields End
        })
             .on('success.field.fv', function(e, data) {
                 if (data.fv.getInvalidFields().length > 0) {    // There is invalid field
                     data.fv.disableSubmitButtons(true);
                 }
             })
             .on('success.form.bv', function (e, data) {
                 // Prevent form submission
                // e.preventDefault();

                 // You can get the form instance
                 var $form = $(e.target);

                 // and the FormValidation instance
                 var fv = $form.data('formValidation');

                 // Do whatever you want here ...
                 RSAPassAndSubmit($("#Password").val(),$("#NewPassword").val(), $("#ConfirmPassword").val(), "@ViewData["Exponent"]", "@ViewData["modulus"]");
                 // Use the defaultSubmit() method if you want to submit the form
                 // See http://formvalidation.io/api/#default-submit

             })

    })

    function RSAPassAndSubmit(PasswordHiddenValue, NewPasswordHiddenValue, ConfirmPasswordHiddenValue, exponent, modulus) {
        setMaxDigits(130);
        var key = new RSAKeyPair(exponent, "", modulus);
        $("#PasswordHiddenValue").val(encryptedString(key,PasswordHiddenValue));
      $("#NewPasswordHiddenValue").val(encryptedString(key,NewPasswordHiddenValue));
        $("#ConfirmPasswordHiddenValue").val(encryptedString(key,ConfirmPasswordHiddenValue));
    }
</script>

說說遇到的一些問題,以及bootstrapValidator的一些常用技巧功能。

  1. 是不是需要等所有的驗證都結束了,才能點擊提交button。所以瘋狂的查啊查,找到了,貌似不太好使,但是不太影響系統安全了。

showing-one-message each time 只能說看了之後很無奈,只是隱藏操作,而不是阻止下一條驗證。所以會有後面Email的的ajax操作,把規則驗證放在後臺也執行一遍,讓註冊提示消息不顯示。

.on('success.field.fv', function(e, data) {
                 if (data.fv.getInvalidFields().length > 0) {    // There is invalid field
                     data.fv.disableSubmitButtons(true);
                }
             })
  1. 先前的密碼加密事件也是放在button上的,要知道有時候那個disable button事件並不好使,所以,所以輸入密碼了過後,一定會直接執行加密方法的,問題就多了。mvc中,後來放了三個hidden字段在form中,把加密的密碼給hidden字段了,頁面輸入只供驗證提示。

api-default-submit

.on('success.form.bv', function (e, data) {
                 // Prevent form submission
                // e.preventDefault();

                 // You can get the form instance
                 var $form = $(e.target);

                 // and the FormValidation instance
                 var fv = $form.data('formValidation');

                 // Do whatever you want here ...
                 RSAPassAndSubmit($("#Password").val(),$("#NewPassword").val(), $("#ConfirmPassword").val(), "@ViewData["Exponent"]", "@ViewData["modulus"]");
                 // Use the defaultSubmit() method if you want to submit the form
                 // See http://formvalidation.io/api/#default-submit

             })

3.支持ajax即使驗證,Remote,驗證郵箱是不是使用過。

Email: {
                    validators: {
                         notEmpty: {
                             message: '請填寫郵箱地址。'
                         },
                         stringLength: {
                             min: 1,
                             max: 128,
                             message: '郵箱地址過長。'
                         },
                         regexp: {
                            regexp: /^(\w)+(\.\w+)*@@(\w)+((\.\w+)+)$/,
                             message: '郵箱格式不正確'
                         }
                         ,
                         remote: {
                           type: "post",
                             url: 'CheckEmailRegisted',
                             data: function (validator) {

                                 return {
                                     email: validator.getFieldElements('Email').val()
                                 };
                             },
                             message: '此郵箱已註冊。',
                             delay: 2000
                        }

                     }
                 },
                 RealName: {
                    validators: {
                         notEmpty: {
                             message: '請輸入真實姓名。'
                         }
                     }
               },

後臺處理Email是否註冊也貼上來吧:

 [HttpPost]
        public JsonResult CheckEmailRegisted(string Email)
        {
            if (!Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
            {
                JsonResult json = new JsonResult { Data = new { valid = true } };
                return json;
              }
             else  if (!_userService.VerifyUserUnicity(Email, Email))
             {
                 JsonResult json = new JsonResult { Data = new { valid = false } };
                 return json;
             }
            else
             {
                 JsonResult json = new JsonResult { Data = new { valid = true } };
                 return json;
        }

        }
        //返回值必須是[valid:true/false]的json串才能被驗證框架識別,然後提示message。

tip:api -using options

$(document).ready(function() {
    $(form)
        .formValidation({
            fields: {
                email: {
                    validators: {
                        emailAddress: {
                            onError: function(e, data) {
                                // Do something ...
                            },
                            onSuccess: function(e, data) {
                                // Do something ...
                            },
                            // ... other validator options ...
                        }
                    }
                }
            }
        });
});

bootsrapValidate自定義自己的規則

官方提供的開發是http://formvalidation.io/developing/,但是有問題(感覺不是一個插件了…)
所以開始的地方自己查開發版的代碼,找到了這種寫法:
$.fn.bootstrapValidator.validators. [validatorname]=…

 $(document).ready(function () {
        //Ourselves Validator rule  for 原密碼和新密碼不能相同
         $.fn.bootstrapValidator.validators.ChangePasswordNOSame = {
            validate: function (validator, $field, options) {
                if ($("#Password").val() == $("#NewPassword").val()) {
                    return {
                        valid: false,    // or false
                        message: '新密碼和當前密碼不能相同'
                    }
                }
                return {
                    valid: true,       // or true
                    message: 'Other  message'
                }
            }
        };

        $('#UpdatePasswordForm').bootstrapValidator
        ({
        ...
        ,
                NewPassword: {
                    validators: {
                        notEmpty: {
                            message: '請輸入新密碼。'
                        },
                        regexp: {
                            regexp: /^((?=.*[a-z])(?=.*[A-Z])(?=.*\W).{8,})$/,
                            message: '密碼格式不符'
                        },
                        ChangePasswordNOSame: {
                        }
                    }
                },
                ...
//但是我發現message在自定義規則上寫了之後,調用的時候不用寫了。。(失誤,直接return:true/flase,就可以在下面寫message了)

感興趣可以仔細看api :http://formvalidation.io/examples/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章