[英]Validating International Telephone Input using jquery validation
極客!
我們都知道一個很棒的插件叫做 International Telephone Input,有沒有辦法將它自己的驗證方法intlTelInput("isValidNumber")
到 jquery 驗證中?
intlTelInput("isValidNumber")
如果為真則返回真,如果為假則返回假
下面還有更多詳細信息!:
var handleContactFormValidation = function () {
var value_form = $('#contact_form');//form i would like to validate where phone field is in!
var value_error = $('.alert-danger', value_form);
var value_success = $('.alert-success', value_form);
value_form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
rules: {
phone: {
required: {
depends: function () {
if ($(this).intlTelInput("isValidNumber") == true)
return true
else
return false
}
}
},
},
現在根據結果“isValidNumber”方法返回我需要將驗證輸出 {true,false} 傳遞給 jquery 驗證,但上面不起作用
這種驗證邏輯毫無意義...
rules: {
phone: {
required: {
depends: function () {
if ($(this).intlTelInput("isValidNumber") == true)
return true
else
return false
}
}
},
},
您編寫它的方式, depends
屬性表示當電話號碼有效時phone
字段是required
,而當電話號碼無效時required
該字段。 要做出此決定,必須填寫該字段。 但是,如果該字段已填寫,則required
規則不再重要。 因此,當它只是留空(沒有有效的電話號碼)時,它不是required
,也不會驗證任何內容。
如果您想驗證與國際電話輸入插件的電話號碼,那么你就需要編寫使用自定義規則.addMethod()
方法調用這個外部.intlTelInput()
方法。
$('#myform').validate({
.....
rules: {
phone: {
required: true, // field is mandatory
intlTelNumber: true // must contain a valid phone number
},
},
....
});
// create a custom phone number rule called 'intlTelNumber'
jQuery.validator.addMethod("intlTelNumber", function(value, element) {
return this.optional(element) || $(element).intlTelInput("isValidNumber");
}, "Please enter a valid International Phone Number");
要在不使用國際電話輸入插件的情況下執行此操作...
jQuery.validator.addMethod("intlTelNumber", function(phone_number, element) {
phone_number = phone_number.replace( /\s+/g, "" );
return this.optional( element ) || phone_number.length > 9 &&
phone_number.match( /^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/ );
}, "Please enter a valid International Phone Number");
此示例顯示美國電話號碼的正則表達式。 修改它以適合您的特定電話號碼要求。 提示:在您的國際電話輸入插件中查看正確的正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.