使用js进行简单的表单验证

时间:2014-02-05 13:04:13

标签: javascript jquery

我正在尝试进行一个非常简单的表单验证,这有点动态。

这是一个字段:

<div class="name">
   <p>Your Name</p>
   <input name="name" type="text" required>
   <span class="validation">You must enter your name</span>
</div>

使用JavaScript如何:查找带有“必需”的输入然后如果“聚焦/点击”并点击掉而不填写它并且必须填充它就在它之后找到它并显示它直到字段被填满。

我尝试了很多方法。

  event.preventDefault();

  var success = true;

   $('#namevalidation').hide();
   $('#emailvalidation').hide();
   $('#messagevalidation').hide();

   if($('#name').val()=='') {
   $('#namevalidation').show();
   success = false;
  }
  if(!IsEmail($('#email').val())) {
  $('#emailvalidation').show();
  success = false;
  }

 if($('#message').val()=='') {
    $('#messagevalidation').show();
    success = false;
}

我找到了这个解决方案,这就是我真正想要的:http://jsfiddle.net/trixta/XqPhQ/问题是,我不知道$.webshims意味着什么......它有什么用?那是Jquery吗?

4 个答案:

答案 0 :(得分:0)

<style>

.error{
    background-color:   #ffffdd;
    border: 1px solid #cacaca;

}
body{
    font-family:Arial, Helvetica, sans-serif;
    font-size:  12px;
}
.valerr{
    color: #D8000C;
    border: 1px solid #872429;
    border-radius: 4px;
    background-image: url('error.png') ;
    background-repeat: no-repeat;
    background-position: 3px 1px;
    background-color: #FFCCB9;
    padding: 3px 3px 1px 25px;
    margin-top: 5px;
}

    var FormValidation = function(form){


         this.messages = {

            required    : 'This field should not be empty',
            email       : 'Please enter  valid email',
            number      : 'Please enter  valid number',
            min         : 'This field length should be minimum ',
            max         : 'This field length should not exceed ',
            range       : 'This field length between  '
        };

        validator = this;

        var currentmsg =this;

        this.required = function(value){
            var valid = (value.length > 0);
            return {status: valid, message: valid ? '' : currentmsg.messages.required};
        }

        this.email = function(value){
            var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ ;
            var valid = pattern.test(value);
            return { status:valid, message: valid ? '' : currentmsg.messages.email};
        }

        this.number = function(value){
            var pattern = /^[0-9]+/ ;
            var valid = pattern.test(value);
            return { status:valid, message: valid ? '' : currentmsg.messages.number};
        }

        this.min = function(value,args){
            if(value.length > 0){
                var valid = (value.length >= args[0])
                return { status:valid, message: valid ? '' : currentmsg.messages.min + args[0] };
            }
        }

        this.max = function(value,args){
                if(value.length > 0){
                    var valid = (value.length <= args[0])
                    return { status:valid, message: valid ? '' : currentmsg.messages.max + args[0] };
                }
            }

        this.range = function(value,args){
            var valid = (value.length >= args[0] && value.length <= args[1])
            return { 
                status:valid, 
                message: valid ? '' : currentmsg.messages.range + args[0] + ' and ' + args[1]
                };
        }

        this.validators = {
            required : validator.required,
            email    : validator.email,
            number   : validator.number,
            range    : validator.range,
            max      : validator.max,
            min      : validator.min 
        };

        this.validate = function(form){
            var elements = form.elements;
            var status = true;
            for(var i = 0; i < elements.length ; i++){
                var validate = elements[i].getAttribute('validate');
                if(!validate){      
                    continue;
                }
                var types = validate.split(' ');
                for(var j = 0; j < types.length; j++){
                    var result = this.validateField(elements[i], types[j]);
                    if(!result) { 
                        continue 
                    }
                    this.displayErrors(elements[i], result);
                    if(!result.status) {                            
                        status = false;
                        break;
                    }
                }
            }
            return status;
        }

        this.displayErrors = function(element, result){
            element.className = result.status ? '' : 'error';
            var elErr =element.errorMsg;
            if(elErr!=null)
                elErr.className = result.status ? '' :'valerr'
                if(!element.errorMsg){
                    elErr = document.createElement("div");
                    elErr.id = 'valerr';
                    element.parentNode.appendChild(elErr);
                    element.errorMsg = elErr;
                }
            elErr.innerHTML = result.message;
        }

        this.validateField = function (element, type){
            var validationType = type;
            var args ;
            if(type.indexOf("(")!= -1 && type.indexOf(")") != -1){
                var result = this.getArguments(type);
                validationType = result.type;
                args = result.argsList;
            }
            validator = this.validators[validationType];
            if(validator != null){
                return validator(element.value ,args);
            }
            return null;
        }

        this.getArguments = function(type){
            var validationtype = type.substring(0,type.indexOf("("));
            var args = type.substring(type.indexOf("(")+1,type.indexOf(")")).split(',');
            return { type : validationtype, argsList : args}
        }

        this.init = function() {
            var curForm = this;
            var forms = document.forms;
            for(var i = 0; i < forms.length ; i++){
                if(forms[i].getAttribute('validate')!=null){
                    forms[i].onsubmit = function(){
                        return curForm.validate(this);
                    };
                }
            }       
        }
}

window.onload = function() {        
    var formValidation = new FormValidation();
    formValidation.init();
}
</script>
<form method="post" action="#" validate>

    <table>
        <tr>
            <td>Name :</td>
            <td><input type="text" name="" validate="required min(5)"></td>
        </tr>
        <tr>
            <td>Mobile No :</td>
            <td><input type="text" name="" validate="required number min(10) max(10)">
        </tr>
        <tr>
            <td>Email :</td>
            <td><input type="text" name="" validate="required email"></td>
        </tr>
    </table>
    <input type="submit"  value="submit"/>
</form>

答案 1 :(得分:0)

请包括

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

代码

答案 2 :(得分:0)

试试这个

$(':required').change(function()
{
    if($.trim($(this).val())==''){$(this).next().val('You must enter your name')}else{$(this).next().val('')}
})

$(':required').blur(function()
{
    if($.trim($(this).val())==''){$(this).next().val('You must enter your name')}else{$(this).next().val('')}
})

答案 3 :(得分:0)

我只使用必需的属性并对其进行验证。我还有一个自定义属性“typeof ='date | time | int'”来验证数据类型。在允许表单提交之前,我在表单字段中循环,如果需要为true但不存在值,则抛出错误。然后检查数据类型是否有效。我通常将错误消息放在title属性中,然后执行.tooltip()来显示错误。

$('input, select, textarea').each(function(){
    var $this =  $(this);
    if ($this.prop('required') == 'true' && $this.val() == '') {
        alert('error')
    }
   // date validations here
});

总是有jquery验证插件,我更喜欢使用我的自定义解决方案,因为我们的数据需要特殊验证。