我正在创建一个带有数字文本框的表单,允许 12 到 30 之间的数字。如果用户输入除此之外的值,它应该提示错误。下面的代码就像这样工作。但加载页面时我不需要此错误。我怎样才能实现它?
代码
<html ng-app="formMod">
<head>
<title>Custom Form Validation</title>
<style type="text/css">
.castIn{
color: red;
display: show;
}
.castAway{
display: none;
}
</style>
</head>
<body ng-controller="formCont as ctrl" >
<form name="myForm" >
How old are you
<input type="number"
class="agee"
required="required"
min="12" max="30"
name="age"
ng-model="user.age">
<span ng-class="ctrl.shouldIshow(user.age)" ng-hide="myForm.agee.$pristine">Age must lie between 12 to 30</span>
</br><input type="submit" name="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script type="text/javascript">
angular.module('formMod',[])
.controller('formCont',[ function(){
this.valueContainer = 'Ms.';
this.shouldIshow = function(age){
return {
castAway : (age >= 12) || (age <= 30),
castIn : (age == null)
};
};
}]);
</script>
</body>
</html>
最佳答案
您在
中将age
拼错为 agee
<span ng-class="ctrl.shouldIshow(user.age)" ng-hide="myForm.agee.$pristine">Age must lie between 12 to 30</span>
angular.module('formMod',[])
.controller('formCont',[ function(){
this.valueContainer = 'Ms.';
this.shouldIshow = function(age){
return {
castAway : (age >= 12) || (age <= 30),
castIn : (age == null)
};
};
}]);
<html ng-app="formMod">
<head>
<title>Custom Form Validation</title>
<style type="text/css">
.castIn{
color: red;
display: show;
}
.castAway{
display: none;
}
</style>
</head>
<body ng-controller="formCont as ctrl" >
<form name="myForm" >
How old are you
<input type="number"
class="agee"
required="required"
min="12" max="30"
name="age"
ng-model="user.age">
<span ng-class="ctrl.shouldIshow(user.age)" ng-hide="myForm.age.$pristine">Age must lie between 12 to 30</span>
<input type="submit" name="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
</html>
关于javascript - Angularjs 隐藏页面加载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061811/