gpt4 book ai didi

javascript - Angular UI 日期选择器在为空时验证为 false

转载 作者:行者123 更新时间:2023-11-30 16:12:40 24 4
gpt4 key购买 nike

我在 Angular 1.4.9 中使用 JqueryUI datepicker(1.0.0) 指令来显示出生日期。此字段不是必需的,除非已填写,否则不应对其进行验证。

页面加载后,该字段被验证为 true(如预期)。一旦用户选择了一个日期,它就会再次有效。但是如果我们手动删除该字段,该字段将变得无效。

<input ui-date="dateOptions" name="dateOfBirth" ng-model="dob"/>

ng-model可以前后设置相同的值,但该值仍然无效。

我创建了一个 JSFiddle 来复制这里的问题。 https://jsfiddle.net/nipuna777/ctsmuv80/

最佳答案

正如@nipuna777 所说,它看起来像是日期选择器中的错误。

我们可以用指令修复它。

jsfiddle 上的实例.

var myApp = angular.module('myApp', ['ui.date']);

myApp.directive('uiDateFix', function($timeout) {
return {
restrict: "A",
require: 'ngModel',
priority: 100,
scope: {
ngRequired: "="
},
link: function(scope, elem, attr, ngModel) {
var originalValidate = null;
$timeout(function() {
if (!originalValidate)
originalValidate = ngModel.$validators.uiDateValidator;
ngModel.$validators.uiDateValidator = function uiDateValidator2(modelValue, viewValue) {
//Define correct validations
if (viewValue || scope.ngRequired)
return originalValidate(modelValue, viewValue);
else
return true;
}
}, 500);
}
}
});
//myApp.factory('myService', function() {});

myApp.controller('MyCtrl', function($scope) {
$scope.name = 'Superhero';
$scope.value = 'Superhero';
$scope.dateOptions = {
changeYear: true,
changeMonth: true,
yearRange: '1900:-0'
};
$scope.isReq = true;
$scope.dob = ""
})
<script src="https://code.jquery.com/jquery-2.2.1.js" charset="utf-8"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-date/1.0.0/date.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">


<body ng-app="myApp">
<div ng-controller="MyCtrl">
<h1> Datepicker</h1>
<form name="person">
<label for="dateOfBirth">Date of Birth: </label>
<input ui-date="dateOptions" name="dateOfBirth" ng-model="dob" ui-date-fix ng-required="isReq" />
<label for="isReq">Required </label>
<input type="checkbox" name="isReq" ng-model="isReq" />
<p>
dob value: {{dob}}
</p>
<p>
dob valid: {{person.dateOfBirth.$valid}}
</p>
<p>
dob errors: {{person.dateOfBirth.$error}}
</p>

<hr>

<h2>Recreating the problem</h2>
<ol>
<li>With the field empty dob is valid</li>
<li>When you select a value from datepicker again the dob field is valid</li>
<li>When dob is manually removed, the field becomes invalid</li>
</ol>

</form>
</div>
</body>

关于javascript - Angular UI 日期选择器在为空时验证为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com