2013-03-23 73 views
-1

嗨我有一個文本框沒有行動按鈕。在打字時,它必須驗證它是否從A到Z,否則它會在文本框旁邊引發錯誤。我怎樣才能做到這一點?jquery文本框驗證

+0

結帳這個.. http://stackoverflow.com/questions/5241957/validate-a-textbox-using-jquery?rq=1 – 2013-03-23 22:40:18

+0

這不是一個我正在尋找。鍵入它的單個文本框必須做兩件事:檢查只輸入a-z,如果沒有,則輸入自身時必須拋出錯誤。 – user2202425 2013-03-23 22:45:37

+0

好吧,我明白了,你會想要使用正則表達式...並將它結合起來.. – 2013-03-23 22:50:49

回答

1

這可能會爲你工作:

<input type="text" class="abc"> 

也許你已經做調整正則表達式,還沒有真正測試過它:

$(document).ready(function() { 
$('.abc').bind('keyup', function() { 
    regex = /^[A-z0-9]+$/; 
    if(!regex.test($(this).val())) { 
     $(this).next('.error').remove(); 
     $(this).after('<div class="error">Wrong</div>'); 
    } else { 
     $(this).next('.error').remove();    
    } 
}); 
}); 

小提琴:http://jsfiddle.net/EB6ET/2/

+0

這就是我正在尋找..感謝:)。你能否單獨改變上述代碼的條件.. 1)只接受一個給z 2)只接受0到9 .. – user2202425 2013-03-23 23:26:38

2

在這裏你去! 我已經讓它變得更簡單,讓人們可以理解的基本邏輯的吧:)

,這裏是我的jsfiddle ..

http://jsfiddle.net/joedf/mhVqr/2/

的Html

<input type='text' id='textbox'> 
<input type="button" class="button-disabled" id="change" disabled="disabled" value="click"> 
<div id="throwEx"/> 

JS

$("#throwEx").hide(); 
$("#textbox").keyup(checkForm).focus(checkForm); 

function checkForm() { 
    var needle = /^([a-zA-Z0-9]+)$/; 
    var inputVal = $("#textbox").val(); 

    if (inputVal == '') { 
     $("#change").addClass("button-disabled").removeClass("button"); 
     $("#change").attr("disabled", "disabled"); 
     $("#throwEx").hide(); 
    } 
    else if (!needle.test(inputVal)) { 
     $("#change").addClass("button-disabled").removeClass("button"); 
     $("#change").attr("disabled", "disabled"); 
     $("#throwEx").text("Error: Only Alphanumeric characters are allowed..."); 
     $("#throwEx").show(); 
    } else { 
     $("#change").removeClass("button-disabled").addClass("button"); 
     $("#change").removeAttr("disabled"); 
     $("#throwEx").hide(); 
    } 
} 
1

我從stackoverflow得到了這個here並已修改,只能輸入字符A到Z。

<input type="text"/> 

$(document).ready(function() { 

$('input').keyup(function() { 
    var $th = $(this); 
    $th.val($th.val().replace(/[^a-z]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; })); 
}); 
}); 

鏈接擺弄here

1

控制使用KEYUP功能的文本框是一個壞主意,因爲用戶可以複製/粘貼文本的文本框內,或選擇瀏覽器的自動完成字段等的一個我做法:

LIVE JSFIDDLE

HTML:

<input type="text" id="TextBox1" name="TexBox1" value="" /> 
<span id='error' name='error'></span> 

JS:

function monitor() { 
    if ($('#TextBox1').val().length > 0) { 
     var reg = /^([a-zA-Z]+)$/; 
     if (!reg.test($('#TextBox1').val())) { 
      $('#error').html("Only letters are allowed!"); 
     } else { 
      $('#error').html(""); 
     } 
    } else { 
     $('#error').html(""); 
    } 
} 

var timer = ''; 

$('#TextBox1').on('focus', function() { 
    timer = setInterval(monitor, 100); 
}).on('blur', function() { 
    clearInterval(timer); 
});