开发者

How to validate input controls in jquery and json, asp.net

开发者 https://www.devze.com 2023-03-25 02:44 出处:网络
I am using jquery and json to save data to the database. How can I apply validation on textboxes. if conditions fails i have applied return false; still json data saving code executes.

I am using jquery and json to save data to the database. How can I apply validation on textboxes. if conditions fails i have applied return false; still json data saving code executes.

$('input[type=text]').each(function() {
                // Ex: Person['FirstName'] = $('#FirstName').val();
                //NewPerson[this.id] = this.value;

                if ($(this).val() == '') {
                    alert('Please Enter ' + this.id);
                    return false;
                }
            });

         var DTO = { 'NewPerson': NewPerson };

            $.ajax({
                type: "POST",
              开发者_高级运维  contentType: "application/json; charset=utf-8",
                data: "{'FirstName':'" + $("#FirstName").val() + "', "
   + "'LastName':'" + $("#LastName").val() + "',"
          + "'Zip':'" + $("#Zip").val() + "'}",

etc.

How to stop datasaving code to execute?


Your each() is closed before the row var DTO = { 'NewPerson': NewPerson};

I think you could refactor your script like this

var isValid = true;
$('input[type=text]').each(function() {
            if ($(this).val() == '') {
                isValid = false;
            }
        });
if(isValid){
    var DTO = { 'NewPerson': NewPerson };
    $.ajax( {type: "POST", 
        contentType: "application/json; charset=utf-8", 
        data: "{'FirstName':'" + $("#FirstName").val() + "', " + "'LastName':'" + $("#LastName").val() + "'," + "'Zip':'" + $("#Zip").val() + "'}"});
}
0

精彩评论

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

关注公众号