能否请您告诉我如何添加验证。在angular js的输入字段中?实际上,我正在制作一个由 json 生成的表单。我已经添加了对必填项的验证。如果用户提交空白值,它会显示“红色边框” 。但是我需要更多的验证方式,例如
我可以在字段中添加自定义验证
http://plnkr.co/edit/YmIMEGHm7E48wZQT9ZSb?p=preview
$scope.isSubmitClicked = false;
$scope.myform =''
$scope.c ={
"ABC": {
"type": "LABEL",
"editable": false
},
"Title": {
"value": "Ms",
"type": "FIELD",
"editable": false,
"dataType": "",
"required":false
},
"First Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
},
"Middle Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":false
},
"Last Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
}
}
$scope.submit = function ($event) {
$scope.isSubmitClicked = true;
};
答案 0 :(得分:0)
您需要创建一个自定义指令,以便在输入字段上进行实时验证。它将根据您的条件为输入字段提供有效的 CSS类,以更改错误警告样式,例如,当字段无效时,您可以将边框设为红色。
假设您知道如何样式移至下一部分:
<input ng-required="true" ng-model="modelName" type="text" abc="modelName">
,您的指令将写为:
App.directive("abc", function() {
return {
require: "ngModel",
//name your scope key and value.
scope: {
abc: "=abc"
},
link: function(scope, element, attributes, modelVal) {
modelVal.$validators.abc= function(val) {
//Write your logic or condition in this function
//return false if invalid and return true if valid.
/*
if(condition)
{
//if true
reutrn true;
}
else{
//if false
return false
}
*/
};
scope.$watch("abc", function() {
modelVal.$validate();
});
}
};
});
,如果您希望表单提交(如果任何字段无效),那么您的表单标签将变为:
<form ng-submit="myForm.$valid && submitFunction()" name="myForm">
请记住在您的表单中提供名称,并使用该名称验证整个表单。
这是您要求@joy的控制器:
var app = angular.module('plunker', ['angularMoment', 'ui.bootstrap']);
app.controller('MainCtrl', function($scope, moment) {
$scope.isEditableMode = true;
$scope.isSubmitClicked = false;
$scope.myform =''
$scope.c ={
"ABC": {
"type": "LABEL",
"editable": false
},
"Title": {
"value": "Ms",
"type": "FIELD",
"editable": false,
"dataType": "",
"required":false
},
"First Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
},
"Middle Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":false
},
"Last Name": {
"value": "",
"type": "FIELD",
"editable": true,
"dataType": "",
"required":true
}
}
$scope.submit = function ($event) {
$scope.isSubmitClicked = true;
};
});
app.directive("checkInput", function() {
return {
require: "ngModel",
//name your scope key and value.
link: function(scope, element, attributes, modelVal) {
modelVal.$validators.checkInput= function(val) {
var numberRegex= /^[0-9]+$/;
if (val.match(numberRegex))
{
return false
}
else{
return true
}
console.log(val);
};
scope.$watch("val", function() {
modelVal.$validate();
});
}
};
});
您的html输入元素:
<input type="text" name="{{key}}" class="form-control" ng-model="value.value" ng-required="value.required && isSubmitClicked" check-input>
希望,我回答了你的问题。接受它,以便我们可以关闭该线程,其他人可以使用此解决方案。