[英]Check for space form validation
我在這里有一個jsfiddle- http://jsfiddle.net/1Lo7ag21/6/
我有一個要輸入名字和名字的名字
我正在嘗試通過檢查空格來驗證名稱字段。
如何檢查該字段是否包含空格,如果沒有,則顯示警報
$('button').click(function(e){
e.preventDefault();
var name = $('#name').val();
if(name.length == 0 && name.indexOf(' ') === -1){
alert('Add first and last name with a space');
}
})
您可以這樣做:
var name = $('#name').val();
name = name.replace(/^\s+|\s+$/g,"") ; // strip any leading or trailing spaces
name = name.replace(/\s+/g," "); // remove multiple intermediate spaces
if (!/(^[A-Za-z]\s[A-Za-z- ']$)/.test(name)) { // first and second names separated by a space, allow for hyphen and apostrophe
alert ("You must enter your first name and last name separated by a space");
}
看起來您已經快到手了,但是您的情況有點差了。
if(name.length == 0 && name.indexOf(' ') === -1){
您正在檢查名稱長度是否均為 0(空字符串) 並且不包含空格。 您可能打算使用||
(或)在這里。
if(name.length === 0 || name.indexOf(' ') === -1){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.