栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

基于angularJS的表单验证指令介绍

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于angularJS的表单验证指令介绍

做开发这么久一直被表单验证这个看似简单又不简单的东西搞得非常烦躁,于是写了个表单验证的框架,再也不用担心这个心烦的验证了。

这里使用AngularJS的指令进行处理代码及其简洁明了

下面是指令JS代码

app.directive('ccForm',['$parse',function ($parse) {
  return {
    restrict:'A',
    link:function (scope,element,attrs) {
      var first=true;
      var errors=0;
      var checkInterval;
      function showError(input,errorIndex) {
 if(first){
   errors++;
   $parse(element.attr('cc-form')).assign(scope,false);
   refreshScope(scope);
   return;
 }
 input.addClass('hasError');
 input.closest('.form-group').addClass('hasError');
 input.next('.help-block').find('.cc-show').removeClass('cc-show');
 input.next('.help-block').find('[cc-error-'+errorIndex+']').addClass('cc-show');
 input.closest('.form-group').next('.help-block').find('.cc-show').removeClass('cc-show');
 input.closest('.form-group').next('.help-block').find('[cc-error-'+errorIndex+']').addClass('cc-show');
      }
      function hidError(input,errorIndex) {
 errors--;
 if(errors==0){
   $parse(element.attr('cc-form')).assign(scope,true);
   refreshScope(scope);
 }
 input.removeClass('hasError');
 input.closest('.form-group').removeClass('hasError');
 input.next('.help-block').find('[cc-error-'+errorIndex+']').removeClass('cc-show');
 input.closest('.form-group').next('.help-block').find('[cc-error-'+errorIndex+']').removeClass('cc-show');
      }
      function checkInput(input) {
 var that=$(input);
 // $('[cc-email]')[0].attributes[0].name
 var attrs=input.attributes;
 var value=that.val();
 for(var i=0,attr;attr=attrs[i];i++){
   if(attr.name=='cc-email'){
     if(/^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$/.test(value)){
hidError(that,attr.value)
     }else{
showError(that,attr.value);
break;
     }
   }else if(attr.name=='cc-phone'){
     if(/d{11}/.test(value)){
hidError(that,attr.value);
     }else {
showError(that,attr.value);
break;
     }
   }else if(attr.name=='cc-max'){
     if(value.length>attr.value){
showError(that,that.attr(attr.name+'-error'));
break;
     }else {
hidError(that,that.attr(attr.name+'-error'));
     }
   }else if(attr.name=='cc-min'){
     if(value.length

对应的需要一点点CSS代码,下面是用LESS写的

.help-block {
 * {
  &:not(.cc-show) {
   display: none;
  }
 }
}

对应的CSS就是

.help-block *:not(.cc-show) {
  display: none;
}

用法1


  test
  

用法2

  

如此简洁明了

以上就是小编为大家带来的基于angularJS的表单验证指令介绍全部内容了,希望大家多多支持考高分网~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/93340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号