-2

I want to do validation Without any plugin as follows in jquery:
1.User Id Cannot Contains Space,
2.Password Must Be greater than Six characters,
3.all Fields are Required.
I can't do this Please Help Me.

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();
    });    

Thanks

JSFiddle

Humayun Ahmed
  • 84
  • 1
  • 11

1 Answers1

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;
});

Try it

http://jsfiddle.net/8ztL653k/

Parfait
  • 1,752
  • 1
  • 11
  • 12
  • Thanks For Your Help But, I Also Want to submit this form to a url(example:'thanks.html') after validations. – Humayun Ahmed Sep 04 '14 at 09:50
  • There are two ways.(1) Submit form with AJAX, and use window.location to redirect page or (2) Submit to server, and redirect at the server side (eg. header("Location:thanks.html") at PHP ) – Parfait Sep 04 '14 at 10:25
  • @Humanyun Ahmed http://stackoverflow.com/questions/25663086/redirection-error-from-one-page-to-another-in-html-and-javascript/25663148 – Parfait Sep 04 '14 at 10:39