以 angularjs 显示提交时的验证错误消息

我有一个表单,需要显示验证错误消息,如果单击提交。

这是一个工作 混蛋

 <form name="frmRegister" ng-submit="register();" novalidate>
<div>
<input placeholder="First Name" name="first_name" type="text" ng-model="user.firstName" required />
<span ng-show="frmRegister.first_name.$dirty && frmRegister.first_name.$error.required">First Name is required</span>
</div>
<div>
<input placeholder="Last Name" name="last_name" type="text" ng-model="user.lastName" required />
<span ng-show="frmRegister.last_name.$dirty && frmRegister.last_name.$error.required">Last Name is required</span>
</div>
<div>
<input placeholder="Email" name="email" type="email" ng-model="user.email" required />
<span ng-show="frmRegister.email.$dirty && frmRegister.email.$error.required">Email is required.</span>
<span ng-show="frmRegister.email.$dirty && frmRegister.email.$error.email">Invalid Email address.</span>
</div>
<input type="submit" value="Save" />
<span ng-show="registered">YOU ARE NOW REGISTERED USER</span>
</form>

当用户开始进行更改时,验证正常工作。但是如果点击提交而没有输入任何内容,它不会显示任何错误消息。

Any thought of achieving this?. Or in other way how can I make each input field $dirty when clicks the Submit button

233881 次浏览

试试这个代码:

<INPUT TYPE="submit" VALUE="Save" onClick="validateTester()">

这个函数将验证您的结果

function validateTester() {
var flag = true
var Tester = document.forms.Tester
if (Tester.line1.value!="JavaScript") {
alert("First box must say 'JavaScript'!")
flag = false
}
if (Tester.line2.value!="Kit") {
alert("Second box must say 'Kit'!")
flag = false
}
if (flag) {
alert("Form is valid! Submitting form...")
document.forms.Tester.submit()
}
}

我可以想出两种方法来实现它。

第一个是删除 novalidate以启用浏览器的验证。

其次,当表单不是这样有效时,您可以禁用 save按钮

<input ng-disabled="!frmRegister.$valid" type="submit" value="Save" />

希望能有帮助。

我发现这个小提琴 http://jsfiddle.net/thomporter/ANxmv/2/,这是一个巧妙的技巧,导致控制验证。

基本上,它声明了一个范围成员 submitted,并在您单击提交时将其设置为 true。模型错误绑定使用这个额外的表达式来显示如下错误消息

submitted && form.email.$error.required

更新

正如在 @ Hafez 的评论中指出的那样(给他一些赞成票!) ,角度1.3 + 解很简单:

form.$submitted && form.email.$error.required

因为我使用的是 Bootstrap 3,所以我使用一个指令: (见 噗通)

    var ValidSubmit = ['$parse', function ($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if(form.$valid) {
fn(scope, {$event:event});
}
});
});
scope.$watch(function() { return form.$valid}, function(isValid) {
if(form.$submitted == false) return;
if(isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
}
}
}
}]


app.directive('validSubmit', ValidSubmit);

然后在我的 HTML 中:

<form class="form-horizontal" role="form" name="form" novalidate valid-submit="connect()">
<div class="form-group">
<div class="input-group col col-sm-11 col-sm-offset-1">
<span class="input-group-addon input-large"><i class="glyphicon glyphicon-envelope"></i></span>
<input class="input-large form-control" type="email" id="email" placeholder="Email" name="email" ng-model="email" required="required">
</div>
<p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.required">please enter your email</p>
<p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.email">please enter a valid email</p>
</div>
</form>

更新

在我最近的项目中,我使用 爱奥尼亚,所以我有以下,它会自动地把 .valid.invalid放在 input-item上:

.directive('input', ['$timeout', function ($timeout) {
function findParent(element, selector) {
selector = selector || 'item';
var parent = element.parent();
while (parent && parent.length) {
parent = angular.element(parent);
if (parent.hasClass(selector)) {
break;
}
parent = parent && parent.parent && parent.parent();
}
return parent;
}


return {
restrict: 'E',
require: ['?^ngModel', '^form'],
priority: 1,
link: function (scope, element, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var form = ctrls[1];


if (!ngModelCtrl || form.$name !== 'form' || attrs.type === 'radio' || attrs.type === 'checkbox') {
return;
}


function setValidClass() {
var parent = findParent(element);
if (parent && parent.toggleClass) {
parent.addClass('validated');
parent.toggleClass('valid', ngModelCtrl.$valid && (ngModelCtrl.$dirty || form.$submitted));
parent.toggleClass('invalid', ngModelCtrl.$invalid && (ngModelCtrl.$dirty || form.$submitted));
$timeout(angular.noop);
}
}


scope.$watch(function () {
return form.$submitted;
}, function (b, a) {
setValidClass();
});




var before = void 0;
var update = function () {
before = element.val().trim();
ngModelCtrl.$setViewValue(before);
ngModelCtrl.$render();
setValidClass();
};
element
.on('focus', function (e) {
if (ngModelCtrl.$pristine) {
element.removeClass('$blurred');
}


})
.on('blur', function (e) {
if (ngModelCtrl.$dirty) {
setValidClass();
element.addClass('$blurred');
}
}).on('change', function (e) {
if (form.$submitted || element.hasClass('$blurred')) {
setValidClass();
}
}).on('paste', function (e) {
if (form.$submitted || element.hasClass('$blurred')) {
setValidClass();
}
})
;


}
};
}])

然后在 HTML:

    <form name='form' novalidate="novalidate" ng-submit="auth.signin(form, vm)">
<label class="item item-input item-floating-label">
<span class="input-label">Email</span>
<input type="email" placeholder="Email" ng-model="vm.email" autofocus="true" required
>
</label>
<button ng-if="!posting" type="submit" class="item button-block item-balanced item-icon-right  call-to-action">Login<i class="icon ion-chevron-right"></i>
</button>

在控制器里:

  self.signin = function (form, data) {
if (!form.$valid) return;


Authentication.emailLogin(data)
//...

所以,现在,在 CSS 中,你可以这样做:

.item.valid::before{
float: right;
font-family: "Ionicons";
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
text-rendering: auto;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #66cc33;
margin-right: 8px;
font-size: 24px;
content: "\f122";
}


.item.invalid::before{
float: right;
font-family: "Ionicons";
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
text-rendering: auto;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #ef4e3a;
margin-right: 8px;
font-size: 24px;
content: "\f12a";


/*
border-left: solid 2px #ef4e3a !important;
border-right: solid 2px #ef4e3a !important;
*/
}

简单多了!

// This worked for me.
<form  name="myForm" class="css-form" novalidate ng-submit="Save(myForm.$invalid)">
<input type="text" name="uName" ng-model="User.Name" required/>
<span ng-show="User.submitted && myForm.uName.$error.required">Name is required.</span>
<input ng-click="User.submitted=true" ng-disabled="User.submitted && tForm.$invalid" type="submit" value="Save" />
</form>
// in controller
$scope.Save(invalid)
{
if(invalid) return;
// save form
}

我最喜欢 真正的人群的溶液。

HTML:

<form role="form" id="form" name="form" autocomplete="off" novalidate rc-submit="signup()">
<div class="form-group" ng-class="{'has-error':  rc.form.hasError(form.firstName)}">
<label for="firstName">Your First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control input-sm" placeholder="First Name" ng-maxlength="40" required="required" ng-model="owner.name.first"/>
<div class="help-block" ng-show="rc.form.hasError(form.firstName)">\{\{rc.form.getErrMsg(form.firstName)}}</div>
</div>
</form>

Javascript:

//define custom submit directive
var rcSubmitDirective = {
'rcSubmit': ['$parse', function ($parse) {
return {
restrict: 'A',
require: ['rcSubmit', '?form'],
controller: ['$scope', function ($scope) {
this.attempted = false;


var formController = null;


this.setAttempted = function() {
this.attempted = true;
};


this.setFormController = function(controller) {
formController = controller;
};


this.hasError = function (fieldModelController) {
if (!formController) return false;


if (fieldModelController) {
return fieldModelController.$invalid && this.attempted;
} else {
return formController && formController.$invalid && this.attempted;
}
};
this.getErrMsg=function(ctrl){
var e=ctrl.$error;
var errMsg;
if (e.required){
errMsg='Please enter a value';
}
return errMsg;
}
}],
compile: function(cElement, cAttributes, transclude) {
return {
pre: function(scope, formElement, attributes, controllers) {


var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;


submitController.setFormController(formController);


scope.rc = scope.rc || {};
scope.rc[attributes.name] = submitController;
},
post: function(scope, formElement, attributes, controllers) {


var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;
var fn = $parse(attributes.rcSubmit);


formElement.bind('submit', function (event) {
submitController.setAttempted();
if (!scope.$$phase) scope.$apply();


if (!formController.$valid) return false;


scope.$apply(function() {
fn(scope, {$event:event});
});
});
}
};
}
};
}]
};
app.directive(rcSubmitDirective);

我的解决方案与引导3

Http://jsfiddle.net/rimian/epxrbzn9/

<form class="form" name="form" ng-app novalidate>
<div class="form-group">
<input name="first_name"
type="text"
class="form-control"
ng-model="first_name"
placeholder="First Name"
required />
</div>
<div class="form-group">
<input name="last_name"
type="text"
class="form-control"
ng-model="last_name"
placeholder="Last Name"
required />
</div>


<button
type="submit"
class="btn btn-primary btn-large"
ng-click="submitted=true">
Submit
</button>


<div ng-show="submitted && form.$invalid" class="alert alert-danger">
<div ng-show="form.first_name.$error.required">
First Name is Required
</div>
<div ng-show="form.last_name.$error.required">
Last Name is Required
</div>
</div>


</form>

在提交表单之前,您只需要检查表单是否脏且有效。

<form name="frmRegister" data-ng-submit="frmRegister.$valid && frmRegister.$dirty ? register() : return false;" novalidate>

你也可以通过以下修改禁用提交按钮:

<input type="submit" value="Save" data-ng-disable="frmRegister.$invalid || !frmRegister.$dirty" />

这个应该能帮你写首字母

我也有同样的问题,我通过添加一个 n- 提交来解决这个问题,它将提交的变量设置为 true。

<form name="form" ng-submit="submitted = true" novalidate>
<div>
<span ng-if="submitted && form.email.$error.email">invalid email address</span>
<span ng-if="submitted && form.email.$error.required">required</span>
<label>email</label>
<input type="email" name="email" ng-model="user.email" required>
</div>


<div>
<span ng-if="submitted && form.name.$error.required">required</span>
<label>name</label>
<input type="text" name="name" ng-model="user.name" required>
</div>


<button ng-click="form.$valid && save(user)">Save</button>
</form>

我喜欢这个想法,使用 $ 递交,我想我已经升级角度到1.3;)

有两种简单而优雅的方法可以做到这一点。

纯 CSS:

在第一次表单提交后,尽管表单有效,Angular 将添加一个 ng-submitted类到刚提交的表单中的所有表单元素中。

我们可以使用 .ng-submitted通过 CSS 控制我们的元素。

如果你只想在用户提交了错误信息后才显示错误信息,例如。

.error { display: none }
.ng-submitted .error {
display: block;
}

使用 Scope 中的值:
在第一次表格提交后,尽管表格有效,角度将设置 [your form name].$submitted为真。因此,我们可以使用该值来控制元素。

<div ng-show="yourFormName.$submitted">error message</div>
<form name="yourFormName"></form>

G45,

我面临同样的问题,我已经创建了一个指令,请检查下面希望它可能有帮助

指令:

    app.directive('formSubmitValidation', function () {


return {
require: 'form',
compile: function (tElem, tAttr) {


tElem.data('augmented', true);


return function (scope, elem, attr, form) {
elem.on('submit', function ($event) {
scope.$broadcast('form:submit', form);


if (!form.$valid) {
$event.preventDefault();
}
scope.$apply(function () {
scope.submitted = true;
});




});
}
}
};




})

HTML:

<form  name="loginForm" class="c-form-login" action="" method="POST" novalidate="novalidate" form-submit-validation="">


<div class="form-group">
<input type="email" class="form-control c-square c-theme input-lg" placeholder="Email" ng-model="_username" name="_username" required>
<span class="glyphicon glyphicon-user form-control-feedback c-font-grey"></span>
<span ng-show="submitted || loginForm._username.$dirty && loginForm._username.$invalid">
<span ng-show="loginForm._username.$invalid" class="error">Please enter a valid email.</span>
</span>
</div>
<button type="submit" class="pull-right btn btn-lg c-theme-btn c-btn-square c-btn-uppercase c-btn-bold">Login</button>
</form>

使用 angularjs 验证表单的完整解决方案。

HTML 如下所示。

<div ng-app="areaApp" ng-controller="addCtrler">
<form class="form-horizontal" name="fareainfo">
<div class="form-group">
<label for="input-areaname" class="col-sm-2 control-label">Area Name : </label>
<div class="col-sm-4">
<input type="text" class="form-control" name="name" id="input-areaname" ng-model="Area.Name" placeholder="" required>
<span class="text-danger" ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"> Field is required</span>
</div>
</div>
<div class="col-sm-12">
<button type="button" class="btn btn-primary pull-right" ng-click="submitAreaInfo()">Submit</button>
</div>
</form>
</div>

AngularJS 应用程序和控制器如下

var areaApp = angular.module('areaApp', []);
areaApp.controller('addCtrler', function ($scope) {
$scope.submitAreaInfo = function () {
if ($scope.fareainfo.$valid) {
//after Form is Valid
} else {
$scope.fareainfo.$setSubmitted();
}
};
});

重要代码段

  1. Ng-app = “ areaApp”ng-controller = “ addCtrler”
    定义角度应用程序和控制器

  2. Ng-show =”(fareainfo. $subited| | fareainfo.name. $Dirty) & & fareainfo.name. $error.demand“
    以上条件确保每当用户第一次看到表单时,屏幕上没有任何验证错误,并且在用户对表单进行更改后,确保验证消息显示在屏幕上。。名称。是 input 元素的 name 属性。

  3. $范围,再见 $有效
    在上面的代码中,每当用户提交表单时,段检查表单是否有效。

  4. $scope.fareainfo. $setSubmit () ;
    在上面的代码中,段确保每当用户提交表单时,所有验证消息都显示在屏幕上,而不需要执行任何操作。