2016-01-08 160 views
0

我有這樣的例子:如何檢查格式是否有效?

link

代碼HTML:

<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890"> 

CODE CSS:

.valid{ 
    border:1px solid green; 
} 
.invalid{ 
    border:1px solid red; 
} 

CODE JS:

$("#primary_phone").blur(function() { 
     text = $(this).val().replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3'); 
     $(this).val(text); 

    if(the form==valid) 
    { 
     addClass.(valid); 
    }else{ 
     addClass.(invalid); 
    } 

}); 

我想要做的是驗證您的...添加紅色邊框,以防拼寫錯誤和格式不受尊重。

我把代碼的想法,我想怎麼做 如果用戶先鍵入正確的形式,然後刪除並寫錯了,我想使代碼無效。

如果您需要更多信息,請讓我知道

在此先感謝!

+0

'addClass(有效);'** => **'$(這).addClass(有效);' – Tushar

回答

1

使它(由:更換.),檢查this

:valid{ 
    border:1px solid green; 
} 
:invalid{ 
    border:1px solid red; 
} 

<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890" pattern="(\d\d\d)(\d\d\d)(\d\d\d\d)"> 

添加pattern屬性爲(\d\d\d)(\d\d\d)(\d\d\d\d),使瀏覽器知道什麼是valid,什麼是invalid

檢查此更新fiddle

0

你可以用regex.test()來檢查格式是否有效,如下所示。如果格式有效,它將返回true,如果無效,則返回false

$("#primary_phone").blur(function() { 
 
    var text = $(this).val(); 
 
    if(text.length==13) return; 
 
    
 
    var isValid = /(\d\d\d)(\d\d\d)(\d\d\d\d)/.test(text); 
 
    if (isValid) { 
 
    $(this).val(text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3')); 
 
    $(this).addClass('valid').removeClass('invalid'); 
 
    } else { 
 
    $(this).addClass('invalid').removeClass('valid'); 
 
    } 
 
});
.valid { 
 
    border: 1px solid green; 
 
} 
 

 
.invalid { 
 
    border: 1px solid red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890">