简体   繁体   中英

what is wrong in this code for validation of controls?

I use jquery for validation of controls:

function RegisterClient() {
    var bookname = true; var edition = true; var author = true; var price = true; var imgType = true; var imgSize = true;

    if (j('#txt_book_name').val() === null) {   //1
        j('#alertBookName').removeClass('hidden');
        bookname = false;
    }
    if (j('#txt_edition').val() === null) {     //2
        j('#alertEditionbook').removeClass('hidden'); edition = false;
    }
    if (j('#txt_author').val() === null) {       //3
        j('#alertAuthor').removeClass('hidden'); author = false;
    }
    if (j('#txt_price').val() === null) {        //4
        j('#alertPrice').removeClass('hidden'); price = false;
    }
    var fileType = j("#ContentPlaceHolder1_FileUpload1").val().split('.').pop().toLowerCase();
    if (j('#ContentPlaceHolder1_FileUpload1').val() != "" && j.inArray(fileType, ['gif', 'png', 'jpg']) == -1)
    { j('#alertImgType').removeClass('hidden'); imgType = false; }
    if (j('#ContentPlaceHolder1_FileUpload1').val() != null) {
        var sizeImg = j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size/1024;
        if (sizeImg > 25) { j('#alertImgSize').removeClass('hidden'); imgSize = false; }
    }
    if (bookname && edition && author && price && imgType && imgSize) __doPostBack('ctl00$ContentPlaceHolder1$Button1', '');

}
  1. In sections 1,2,3,4, the (j('#txt_...').val() === null) statement does not work correctly.

  2. The (var sizeImg = j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size/1024;) statement has an error, shown when using firebug. I can show the value of j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size with Alert() , but there is an error.

Regarding your first problem:

The only that this is possible is that if condition gets executed before the user inputs anything.

I have made a fiddle to explain it:

https://jsfiddle.net/tr91Lw7y/

Run this and you will see "johndoe" instantly.

But if you run this:

http://jsfiddle.net/6mjgx2r4/

You will see blank anytime you do this.

There is one solution to your problem if you cannot adjust the flow:

$("#txt_book_name").keyup(function(){
        if($(this).val() === null) {
         // Conditions
        }
});

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