2016-08-10 46 views
-4

優惠券代碼驗證funcanality

function validate(coupon) { 
 
    var myRe = "LUCKY100"; 
 
    if(cvv.value.match(myRe)) { 
 
     return true; 
 
    } else { 
 
     document.getElementById('couponerror').innerHTML="Invalid coupon"; 
 
     return false; 
 
    } 
 
}
<form onsubmit="validate(coupon)"> 
 
<label style="width:50px;"><input type="text" name="coupon" class="coupon" title="Enter coupon" o > 
 
</p><span id="usernameError"></span></label> 
 
<input type="button" value="Submit" />

我是新來的jQuery我的問題是我需要一個copon代碼驗證方法,像我給你的優惠券代碼,LUCKY100 &如果用戶在輸入輸入鍵入不同的值,它給出下面的錯誤信息輸入字段不提醒&如果用戶輸入LUCKY100它給予消息優惠券申請成功。請提供我這個驗證的HTML和JavaScript或jQuery。 在此先感謝

+0

你試過了什麼? –

+0

從哪裏可以得到正確的值,以便與用戶在輸入時輸入的內容進行比較? – FDavidov

+0

我將分配LUCKY100在JS或JQ @FDavidov –

回答

0

試試這個,

function validate(coupon) { 
 
    var myRe = "LUCKY100"; 
 
    var coupon = myRe.trim(); 
 
    var input = document.getElementById('in').value; 
 
    if(input.toUpperCase() == coupon.toUpperCase()) { 
 
     document.getElementById('message').innerHTML="Coupon applied!"; 
 
     document.getElementById('err').innerHTML=""; 
 
     return true; 
 
    } else { 
 
     document.getElementById('err').innerHTML="Invalid coupon"; 
 
     document.getElementById('message').innerHTML=""; 
 
     return false; 
 
    } 
 
}
#message{ 
 
    position: relative; 
 
    top: 10px; 
 
    color:green; 
 
} 
 
#err{ 
 
    position: relative; 
 
    top: 10px; 
 
    color:red; 
 
}
<form onsubmit=""> 
 
<label style="width:50px;"><input type="text" name="coupon" id="in" class="coupon" title="Enter coupon" > 
 
<span id="usernameError"></span></label> 
 
<input type="button" value="Submit" onClick="validate(coupon)" /></form> 
 

 
<span id="message"></span> 
 
<span id="err"></span>

希望有幫助!

+0

用戶請求的jQuery ...'var input = $('#in')[0 '.value();'please please;) –

+0

謝謝@Hitesh,請告訴我一件事,如果用戶在sentitive情況下輸入優惠券,它也應該像Lucky100或lucky100一樣應用 –

+0

您可以使兩個參數都爲低或大寫使用toUpperCase()或toLowerCase()方法檢查,我已經更新了我的答案並檢查了它 –

0

根據您的代碼,正確的值是硬編碼。假設你想不區分大小寫的檢查:

  1. 添加輸入元素:

,並在您的JS:

: 
if (document.getElementById("userInput").value != "undefined") { 

    if (document.getElementById("userInput").value.toUpperCase() == "LUCKY100") { 

     return true ; 
    } else { 
     return false ; 
} 
: 
+0

請爲我提供完整的JS與HTML作爲錯誤消息不顯示@FDavidov –

+0

您可以部署帶有ID和更改該值(再次使用'document.getElementById(...)。value = ...')更新錯誤消息(在發生錯誤時爲null或實際消息)。 – FDavidov

+0

user requested jQuery ...''('#userInput')[0] .value()。toUpperCase()'please;) –