javascript validate function

String.prototype.validate = function(type){  
    var pattern = new Array();

    pattern['email'] = /^w[w-.][email protected]+(.w+)+$/;
    pattern['url'] = /^http://w+.w+/?.*$/;
    pattern['password'] = /^[w.]+$/;
    pattern['id'] = /^[a-zA-Z][0-9]{9}$/;

    return this.match(pattern[type]);

昨天寫的一個用來檢查輸入的函式, 直接掛在 String Object 下面, 這樣就可以直接這樣使用:
如, 檢查 email 是否正確

"[email protected]".validate('email');



如果回傳值為 null 那就是錯誤啦! 不過 regular expression 的 pattern 還需要改進就是了~


Read more posts by this author.

Subscribe to Oceanic / 海海人生

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!