• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Angualrjs 表单验证的两种方式(失去焦点验证和点击提交验证)

angularjs 搞代码 4年前 (2021-12-31) 30次浏览 已收录 0个评论

AngularJS提供了表单验证,但是验证的过程交互体验很不好,比如重设密码,重复密码的时候一键入就会提示密码不正确。现在小编给大家整理了两种方法,需要的的朋友参考下吧

AngularJS提供了表单验证,但是验证的过程交互体验很不好,比如重设密码,重复密码的时候一键入就会提示密码不正确,现整理了两种方法,仅供借鉴。

一,点击提交验证

  <div class="form-group"> <label class="col-sm-2 control-label">密码</label><div class="col-sm-8"> </div></div><div class="form-group"> <label class="col-sm-2 control-label">重复密码</label><div class="col-sm-8"> </div><span style="color:red">密码不一致</span></div><div class="form-group"> <button type="submit" class="btn btn-primary">确认</button><button type="button" class="btn btn-default">取消</button></div>

当用户试图提交表单时,你可以在作用域中捕获到一个submitted值,然后对表单内容进行验证并显示错误信息。

JS代码

 $scope.submitted = false; $scope.resetPwd = function(){ console.log(666); if($scope.reset_pwd.$valid && $scope.mycompwd == $scope.resetmycompwd){ console.log('重置成功,进行其他操作'); }else{ $scope.reset_pwd.submitted = true; } }

亲测可用。

第二种失去焦点验证

  <div class="form-group"> <label class="col-sm-2 control-label">密&nbsp&nbsp码</label><div class="col-sm-8"> </div></div><div class="form-group"> <label class="col-sm-2 control-label">重复密码</label><div class="col-sm-8"> </div><span style="color:red">密码不一致</span></div><div class="form-group"> <button type="submit" class="btn btn-primary">确认</button><button type="button" class="btn btn-default">取消</button></div>

JS代码

 app.directive('ngFocus',[function(){ var focusClass = 'ng-focused'; return{ restrict:'AE', require:'ngModel', link:function(scope,element,attrs,ctrl){ ctrl.$focused = false; element.bind('focus<em style="color:transparent">来源gao.dai.ma.com搞@代*码网</em>',function(e){ element.addClass(focusClass); scope.$apply(function(){ ctrl.$focused = true; }); element.bind('blur',function(e){ element.removeClass(focusClass); scope.$apply(function(){ ctrl.$focused = false; }); }); }) } }; }]);

注意HTML标红的地方。正是区分两种方法的关键。

以上就是Angualrjs 表单验证的两种方式(失去焦点验证和点击提交验证)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Angualrjs 表单验证的两种方式(失去焦点验证和点击提交验证)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址