开发者

what is the "right" way to do form validation with javascript?

开发者 https://www.devze.com 2023-03-24 00:27 出处:网络
I am doing some form validation on a project with javascript. what im doing works but it seems like there might be a better way to do it.here is an example of what i have.

I am doing some form validation on a project with javascript. what im doing works but it seems like there might be a better way to do it. here is an example of what i have.

onkeypress="return keyNumOnly(event)"
function keyNumOnly(key)
{//this allows numbers and decimals.   
    var keychar;
    var numcheck;
    var keynum;
    if(window.event) // IE
        {
            keynum = key.keyCode开发者_运维问答;
        }     
    else if(key.which) // Netscape/Firefox/Opera
        {
            keynum = key.which;
        }
    if (keynum==8)
        {
            return true;
        }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;
    if (keychar== ".")
        {
            return true;    
        }
    return numcheck.test(keychar);
}


Some cleanup:

someTextbox.onkeypress = function(event) { // you can pass a function directly
    var event    = event || window.event, 
        // this means: event or window.event if event does not exist

        keynum   = event.keyCode || event.which,
        // event.keyCode or event.which otherwise

        keychar  = String.fromCharCode(keynum),

        numcheck = /\d/;


    if(/\t|\./.test(keychar)) {
        // checking for dot or tab using a regexp: \t is tab, | means 'or', \. is dot
        return true;
    }


    return numcheck.test(keychar);
}


I suggest using a pre-packaged solution to do form validation. For example, if you can use jQuery the jQuery Validation Plugin does a great job of validating forms - both live validation (like it looks like you are doing) as well as validation prior to a 'submit' event.


Form valiation (e.g. against regexes) is part of HTML5, and hence can soon be done by the browser itself.

Dive into HTML5 explains how

0

精彩评论

暂无评论...
验证码 换一张
取 消