简体   繁体   中英

Form Fields Validation Through Javascript

I'm making a form and i want when the fields are empty the border of the fields gets red but my code is not working please help ! i'm using bootstrap and jquery framework

MY JQUERY

$('document').ready(function() {

    $("#form").submit(function() {

        var username = $("#username").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var confPassword = $("#confPassword").val();
        var message = $("#warning");

        if (username == "" && email == "" && password == "" && confPassword == "") {
            return false;
            $("#username").css("border", "1px solid red");
        } else {
            return true;
        }

    });

});

return after setting the css rule. Once the return statement is executed none of the statement after it in the function is executed because the control flow is returned to the caller by the return call.

$('document').ready(function () {

    $("#form").submit(function () {

        var username = $("#username").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var confPassword = $("#confPassword").val();
        var message = $("#warning");

        if (username == "" && email == "" && password == "" && confPassword == "") {
            $("#username").css("border", "1px solid red");
            return false;//return after setting the properties
        } else {
            return true;
        }

    });

});

Use OR || to check if user has entered text.

if (username == "" || email == "" || password == "" || confPassword == "" || password != confPassword) {

Adding to avoe answer try code so you should not have to write line of code for each text box,

var isvalid = true;
$("#username, #email, #password, #confPassword, #warning").each(
function()
{
  if($(this).val()==="")
  {
    $(this).css("border", "1px solid red");
   isvalid = false;
  }
}
);
return isvalid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM