Form validation in jQuery without using plugin

前端 未结 4 1557
悲&欢浪女
悲&欢浪女 2020-12-19 07:50

I want to perform client-side validation of a simple form using jQuery, but I can\'t use any plugins for validation. I want to display any error messages in a single alert

4条回答
  •  一整个雨季
    2020-12-19 08:24

    Loop through each input element in the form, and check if it has a value. If not append the error message to a string which you later alert out if valid is false.

    $('#submit').on('click', function() {
        var valid = true,
            message = '';
    
        $('form input').each(function() {
            var $this = $(this);
    
            if(!$this.val()) {
                var inputName = $this.attr('name');
                valid = false;
                message += 'Please enter your ' + inputName + '\n';
            }
        });
    
        if(!valid) {
            alert(message);
        }
    });
    

    Fiddle: http://jsfiddle.net/WF2J9/17/

提交回复
热议问题