2013-07-15 33 views
-2

http://jsfiddle.net/ZKsjr/ 我正在使用此腳本,它能夠正確驗證輸入字段,但我試圖實現一個新功能,以便重置爲原始值名稱(名字)如果信息不正確已經被使用過(var reg =/^ [az,.'-] + $/i;)但是這需要在完成輸入(模糊)之後發生,你會知道如何解決這個問題嗎?文本輸入驗證

<!DOCTYPE html> 

<html> 

<head> 

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title> - jsFiddle demo</title> 
    <script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>  
    <link rel="stylesheet" type="text/css" href="/css/result-light.css"> 

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){ 
function isfname(text){ 
    var reg = /^[a-z ,.'-]+$/i; 
    return reg.test(text); 
} 

$(".fname").keyup(function(e) { 
    var $test = $(this); 
    if (isfname($test.val())) { 
     $test.css("border-color", "rgb(140, 202, 165)"); 
     $test.css("background-color", "rgb(140, 202, 165)"); 
     $test.css("color", "black"); 

    }else{ 
     $test.css("background-color", "rgb(198, 95, 88)"); 
     $test.css("border-color", "rgb(198, 95, 88)"); 
     $test.css("color", "black"); 
    } 
}).blur(function(e) { 
    $(this).css("background-color", ""); 
    $(this).css("border-color", ""); 
    $(this).css("color", ""); 


}); 




});//]]> 

</script> 


</head> 

<body> 

    <input type="text"id="element_2_2" class="fname" maxlength="255" size="8" " value="First Name" 
onblur="if (this.value == '') {this.value = 'First Name';}" 
onfocus="if (this.value == 'First Name') {this.value = '';}" required/> 


</body> 

</html> 
+0

是的,PHP或其他一些服務器端腳本。 Javascript不適合驗證,因爲它可以被停用。檢查[在這個問題中的警告](http://stackoverflow.com/q/3602530/938236) –

+0

我不會單獨使用JavaScript,我遇到的問題是模糊函數將背景和邊框顏色設置爲它的默認值很好,但如果有人輸入了無效數據,它不會重置默認值。 –

+1

@Francisco那麼,只要您使用服務器端驗證進行備份,客戶端驗證_is_很有用。 :) – doppelgreener

回答

0

入住.blur字段值和字段的值設置爲First Name

就像這個...

.blur(function(e) { 
    $(this).css("background-color", ""); 
    $(this).css("border-color", ""); 
    $(this).css("color", ""); 
    if(!isfname($(this).val())) 
     $(this).val('First Name'); 
}); 

updated jsFiddle Demo

+0

我正在嘗試在用戶點擊輸入字段後執行此操作,您正在執行的操作是在鍵入時將值重設爲名。 –

+0

查看我更新的答案和jsFiddle。 – neo108

+0

你是一個有天賦的個人感謝! –