2014-10-30 88 views
2

我想在用戶輸入的單詞末尾驗證結尾「uu」,「ha」和「cross」...請參閱「腳本」標籤中的「//」我的意思:)驗證結束字母只有

這是我的HTML表單:

<form name="myForm" action="haha.php" onsubmit="return validateForm()" method="post"> 
    <p id="text">Something: </p> 
    <input type="text" name="form" id="box" > 
    <input type="submit" value="Submit" id="but" > 
</form> 

<p id="check"></p> 

我的Java腳本驗證...

function validateForm() { 
    if(document.myForm.form.value == "") { 
     document.getElementById('check').innerHTML = 'Please fill in the form:) '; 
     return false; 
    } 

    //ok so here's an example of what I'm trying to achieve... 
    if(document.myForm.form.value == endings "uu" "ha" cross") --//please correct- endings "uu" "ha" cross" -- { 
     return true; 
    } 
} 

回答

1

嘗試使用正則表達式來測試串的一端給出的子串:

if (/(uu|ha|cross)$/.test(document.myForm.form.value)) { 
    return true; 
} 
+0

這不適用於匹配單詞的*結尾*。例如,「Happy」返回true,因爲它包含「ha」。也許它需要在uu和ha結尾處的$? – Zack 2014-10-30 19:25:12

+1

也許你的意思是'/(uu | ha | cross)$ /'? – 2014-10-30 19:26:16

+0

耶夥伴那樣的問題,你知道該怎麼做 - 扎克? – 2014-10-30 19:26:40

1
if(submittedValue.slice(-2) == "uu" || submittedValue.slice(-2) == "ha" || submittedValue.slice(-5) == "cross")  { 
    return true; 
} 
+0

Thankanks Zack幫了我:) – 2014-10-30 19:30:01