2017-08-29 66 views
-2

如何使用Regex進行驗證並對com.開始進行自己的驗證,您能否給我提供一些我希望驗證文本字段的示例。 文本字段必須以com開頭。使用JQuery對文本字段進行自定義驗證

<input id="appPackage" name="appName" type="text" data-error=".errorTxt1"> 

我曾嘗試下面的代碼:

jQuery.validator.addMethod("appPackage", function(value, element) { 
     return jQuery.validator.methods['appPackage'].call(this, value, element) || value == ("com."); 
    }, "Please enter a valid with (com.)."); // connect it to a css class jQuery.validator.addClassRules({ appPackage : { appPackage : true } }); 

Text Field input

+0

使用jQuery的驗證與rezex –

+0

告訴我們,到目前爲止,你已經嘗試了代碼。 – neuhaus

+0

https://www.w3schools.com/Jsref/jsref_obj_regexp.asp - https://www.w3schools.com/js/js_validation.asp - 玩得開心 – Alexis

回答

0

入住這個環節的工作regexWorking Regex

嘗試以下解決方案:

$.validator.addMethod("appName", function(value, element) { 
    var val = '' 
    // var customError = ""; 
    if (value.match(/^com\./)) 
    { 
     val = true; 
    } else { 
     val = false; 
    } 

    return val; 
}, 'Please enter a valid app name which start with (com.).'); 

HTML代碼:

<input id="appPackage" name="appName" type="text" data-error=".errorTxt1"> 
+0

'.'需要轉義,因爲它是正則表達式中的通配符。 –

+0

@PeterB,我不夠好的正則表達式,你可以請編輯我的答案,如果我在正則表達式錯誤 –

+0

非常感謝@chiragsatapara偉大的工作...(Y) –

0

使用該JavaScript代碼來驗證。

var value=document.getElementById("your_field_id").value; 
var n = value.startsWith("com"); 

這裏n將返回true,如果有效數據

0

你可以試試這個布爾值,

var SiteAddress = "com.url.abc"; 
var SiteAddressTemp = "abc.com.url.abc"; 
var SiteAddressRegx = /^com/; 
alert(SiteAddressRegx.test(SiteAddress)); //true 
alert(SiteAddressRegx.test(SiteAddressTemp)); //false