2015-10-27 171 views

回答

1

你爲什麼不只是使用HTML5模式驗證?這很容易,沒有Javascript來維持。

演示片段:

<form> 
 
    <input type="text" name="one" pattern=".*,$" /> 
 
    <input type="submit" value="Submit" /> 
 
</form>

1

您可以使用includes()

var str = 'hello world,' 
 
if (str.includes(',',-1)) alert ('valid')

請注意,includes是es6的一項功能,只能在現代瀏覽器中使用,請參閱上面發佈的鏈接以獲取更多信息和填充。

+0

你還應該注意到,這是一個ES6功能,他應該在服務器端做這樣的驗證,如果代碼甚至會是javascript,那麼問題。如果它是nodeJS,那麼它應該是'.contains',否則就是PHP中的某些東西...... –

0

HTML:

<form name="myForm"> 
    <input type="text" name="one" onkeypress="validateForm()"> 
    <input type="submit"> 
</form> 

JS:

function validateForm() { 
    var x = document.forms["myForm"]["one"].value; 
    if(x.charAt(x.length-1) == ','){ 
    console.log("true"); 
    }else{ 
    console.log("false"); 
    } 
} 
-1
/,$/.test("hello world,") // true 
+1

爲什麼要使用正則表達式?爲什麼? –

+0

@MaxMastalerz它簡短,靈活,不會破壞舊版瀏覽器。爲什麼不? – brannigan

+0

@MaxMastalerz你爲什麼不使用正則表達式? –

1

這可以使用HTML5的輸入pattern屬性,驗證輸入與正則表達式來完成。該表格將不會被允許在現代browsers that support this attribute提交 - 但要始終驗證用戶輸入的服務器端也是如此。

input:valid { 
 
    background: lime; 
 
} 
 

 
input:invalid { 
 
    background: red; 
 
}
<input type="text" pattern="(.+?),$">

在這個例子中使用的CSS純粹是顯示當輸入是有效的(綠色)。

0

有javascript函數的endsWith該檢查是字符串,某些字符

var chr = "Hello world,"; 
    if(chr.endsWith(",") { 

    }else{ 

    } 

爲肯尼表示,在IE瀏覽器不會工作結束。 。MDN提供protoype功能此功能

if (!String.prototype.endsWith) { 
    String.prototype.endsWith = function(searchString, position) { 
     var subjectString = this.toString(); 
     if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { 
     position = subjectString.length; 
     } 
     position -= searchString.length; 
     var lastIndex = subjectString.indexOf(searchString, position); 
     return lastIndex !== -1 && lastIndex === position; 
    }; 
} 
+0

只是一個人擡頭,這個解決方案在IE中不起作用。 –

0

最基本的方法是類似的Marcin C'S:

function endsWith(str, end) { 
    var $len = str.length, 
    $endlen = end.length; 
    if (substr($len - $endlen, $endlen) === end) { 
     return true; 
    } else { 
     return false; 
    } 
} 
0

我要補充的ID,爲了容易地提取的值:

var textInputValue = document.getElementById("myIdHere").value; 

然後使用正則表達式來看看它的模式匹配:

if(textInputValue.match(/,$/)){ 
    alert("the input is valid!"); 
} else { 
    alert("sorry, invalid input"); 
} 

這裏是一個小提琴:http://jsfiddle.net/ybsuyx6e/

相關問題