【问题标题】:Angular custom form validation message not showing up on 1 specific fieldAngular 自定义表单验证消息未显示在 1 个特定字段上
【发布时间】:2018-12-25 09:56:39
【问题描述】:

我有一个 Angular 表单,其中包含(以及其他)2 个看起来像这样的元素:

邮编:

<label class="item item-input" ng-class="{ 'has-error' : registrationForm.postcode.$invalid && (registrationForm.postcode.$dirty || submitted)}">
    <span class="input-label">Postcode<span class="required">*</span></span>
    <input ng-change="test()" name="postcode" type="text" ng-model="registration.postcode" required ng-pattern="postcode_regex" autocomplete='postal-code'>
</label>
<p ng-show="profileForm.postcode.$invalid && (profileForm.postcode.$dirty || submitted)" class="assertive">A valid postcode is required.</p>

电话:

<label class="item item-input" ng-class="{ 'has-error' : registrationForm.telephone.$invalid && (registrationForm.telephone.$dirty || submitted)}">
    <span class="input-label">Telephone<span class="required">*</span></span>
    <input ng-change="test()" name="telephone" type="tel" ng-model="registration.telephone" required ng-pattern="phone_number_regex" autocomplete='tel'>
</label>
<p ng-show="registrationForm.telephone.$invalid && (registrationForm.telephone.$dirty || submitted)" class="assertive">A valid telephone is required (numbers only please).</p>

相关的控制器代码如下所示:

$scope.phone_number_regex = /^[0-9 ]{10,}$/;
//https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
// (Note: I tested this on regex101.com and it works fine).
$scope.postcode_regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})$/; 

$scope.submit = function (isValid) {
    $scope.submitted = true;
    if (isValid) {

等等

当用户完成电话字段时,一旦他们开始输入,验证消息(即“需要有效的电话等...”)就会出现,直到它与 $scope.phone_number_regex 匹配。但是,在邮政编码字段上,不会显示任何验证消息(即“需要有效的邮政编码。”),但是在与 $scope.postcode_regex 匹配之前,表单不会提交。

为什么我没有看到邮政编码的验证消息?

【问题讨论】:

    标签: angular validation


    【解决方案1】:

    表单名称有冲突。希望您在这里使用registrationForm 而不是profileForm

    profileForm.postcode.$invalid 更改为registrationForm.postcode.$invalidprofileForm.postcode.$dirty 更改为registrationForm.postcode.$dirty

    <p ng-show="registrationForm.postcode.$invalid && (registrationForm.postcode.$dirty || submitted)" class="assertive">A valid postcode is required.</p>
    

    希望对您有所帮助!

    【讨论】:

    • 感谢@coder!我不知道我读了多少次并错过了它!
    • @Mr Benn 很高兴为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2017-09-30
    • 1970-01-01
    • 2023-03-11
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多