简体   繁体   English

使用js进行简单表单验证

[英]Simple form validation using js

I am trying to make a very simple form validation that is a bit of dynamic. 我正在尝试进行非常简单的表单验证,该验证有点动态。

Here is a field: 这是一个字段:

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

Using JavaScript how to: Find input with "required" then if "focused/clicked" and clicked away without filling it and it has to be filled find the span just after it and show it until the field is filled. 使用JavaScript的方式:查找带有“必填”的输入,然后如果未选中“已聚焦/单击”并单击并单击而不填充它,则必须填充它,然后在其后找到跨度并显示它,直到填充字段为止。

I have tried many methods for example. 例如,我尝试了许多方法。

  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;
}

I found this solution, which is what I actually want: http://jsfiddle.net/trixta/XqPhQ/ The thing is, I have no idea what $.webshims means... What does it use? 我找到了这个解决方案,这是我真正想要的: http : //jsfiddle.net/trixta/XqPhQ/事实是,我不知道$.webshims是什么意思……它有什么用? is that Jquery? 那是Jquery吗?

<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>

please include 请包括

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

in your code 在你的代码中

try this 尝试这个

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

and

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

i just use the required attribute and validate against that. 我只是使用所需的属性并对此进行验证。 i also have a custom attribute "typeof='date|time|int'" to validate data types. 我也有一个自定义属性“ typeof ='date | time | int'”来验证数据类型。 before allowing form submission, i do a loop through the form fields and if required is true but no value exists, throw an error. 在允许提交表单之前,我在表单字段中进行了循环,如果要求为true,但不存在任何值,则抛出错误。 then check the data types for valid data. 然后检查数据类型以获取有效数据。 i usually put the error message in the title attribute then do .tooltip() to display the error. 我通常将错误消息放在title属性中,然后执行.tooltip()来显示错误。

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

there is always the jquery validation plugin as well, i just prefer to use my custom solution since our data needs special validations. 总有一个jquery验证插件,我更喜欢使用我的自定义解决方案,因为我们的数据需要特殊的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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