在没有插件的Jquery中验证

时间:2014-09-03 09:45:08

标签: jquery


我想在jquery中执行验证而不使用任何插件,如下所示:
 1.用户ID不能包含空格,
 2.Password必须大于六个字符,
 3.所有字段都是必需的。
我不能这样做请帮助我。

Jquery的:

$('#form').submit(function (event) {
    //getting elements
    var id=$('#userId').val();
    var pw=$('#pw').val();
    //validating

    //$('span').text('These Fields Are Required...').show().fadeOut(100);


    if ( id !== "" && pw !=="") {
        var json={'User Id':id,'Password':pw};
        $.each(json,function(p,v){
            alert(p+": "+v);
        });
        return;
    }
    else if( id.indexOf(' ')>=0 ){
        $( "span" ).text( "User Id Cannot Contain Space!" ).show().fadeOut( 1000 );
    }       
    if(id==="" || pw==="")
    {
        $( "span" ).text( "Some Feilds are Required!" ).show().fadeOut( 1000 );
    }
    event.preventDefault();
    });    

感谢

JSFiddle

1 个答案:

答案 0 :(得分:0)

$('#form').submit(function (e) {
    e.preventDefault();

    //getting elements
    var id = $('#userId').val();
    var pw = $('#pw').val();

    //validating
    try {
        //all Fields are Required.
        $(".required").each(function () {
            if ($(this).val().length == 0) {
                $(this).focus();
                throw "Some Feilds are Required!";
            }
        });

        //User Id Cannot Contains Space
        var userid_ppt = /^\w+$/g;
        if( !userid_ppt.test(id) )
            throw "User Id Cannot Contains Space";

        //Password Must Be greater than Six characters
        if( pw.length < 6 )
            throw "Password Must Be greater than Six characters";

    } catch (emsg) {
        $("#msg").html(emsg).stop().show().fadeOut(1000);;
        return false;
    }
    return true;
});

试试吧

http://jsfiddle.net/8ztL653k/