[英]Custom form validation using jquery plugin, based on attributes
我正在使用Jquery valdiation插件在客戶端驗證表單。 但是我想做類似的驗證。
<input type="text" id="txtInf" regex="/some regular expression/" error="Inf is mandatory"></inf>
regex和error是自定義屬性。 該字段將針對正則表達式中的給定正則表達式進行驗證,如果正則表達式文本失敗,則應顯示錯誤消息。
我試圖像這樣向驗證器添加方法。
$("*[regex]").each(function () {
$.validator.addMethod($(this).attr('id'), function () {
return this.optional($(this)) || $(this).attr('regex').test($(this).text());
}, $(this).attr('error'));
});
但是這種方法存在一些問題。 如果我認為正確的話,請告訴我。 如果您有其他選擇,請告訴我。 歡迎任何思考過程。
我沒有使用過該插件,但看起來您會因為使用test()而收到錯誤消息。
$(this).attr('regex').test($(this).text());
應該
var regEx = new RegExp($(this).attr('regex'));
regEx.test($(this).text());
只需幾行代碼,即可在引導程序中進行自定義表單驗證
//在html中添加以下代碼
<form id="addForm" action=" " method="post" class="needs-validation" novalidate> </form>
//將其添加到腳本標簽中
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
document.getElementById("btn_inject").addEventListener("click", function(event) {
//form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})
();
//您還需要使用它來使文本框變回原來的狀態
$("#Modalidname").on('hide.bs.modal', function() {
$("#Formidname").removeClass('was-validated');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.