[英]Validate first 2 characters of a textfield
我有一個文本框,用戶需要輸入他/她的手機號碼。 但是,我需要驗證前兩個數字(字符),以確保手機號碼的格式正確(作為驗證規則之一)。
手機號碼必須以以下兩位數字開頭:
44xxxxxx 55xxxxxx 65xxxxxx 78xxxxxx
誰能告訴我如何驗證前兩個字符的編號並檢查它們是否為上述選項之一?
編輯這是我嘗試過的,但是沒有用:
的HTML
<input id="mob" name="mob" type="tel" placeholder="Enter your mobile number">
<a href="#" id="validate">Validate</a>
JS
var mobile_prefix = $('#mob').subsubstr(0,2);
$('#validate').click(function(){
if (mobile_prefix == 44||55||65||78) {
alert('correct');
}
else {
alert('incorrect');
}
});
使用正則表達式可能是最簡單的:
({phone number}).match(/^(44|55|65|78).*$/)
使用javascript中的substring
var FirstTwoLetters = TextFromYourInput.substring(0,2);
然后您可以將前兩個字母與您的模式進行比較。
因此,輸入的第一個變量已提交;請留意;)首先檢查該輸入是否不為空並且具有3個或更多符號。 最后是變量,我最后使用它允許form.submit()。 如果您願意,可以在每次獲取val() $.trim(postcode.val()) != ''
之前添加
var postcode = $('#post_code');
if(postcode.val() != '' && postcode.val().length > 2){
var shortPostCode = postcode.val().substring(0,2);
var validPostCode = /^(EH|KY)/;
if(!shortPostCode.match(validPostCode)){
postcode.after('<span class="error">Post code must start with EH</span>');
dataValid = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.