developer tip

Angularjs 동적 ng- 패턴 유효성 검사

optionbox 2020. 9. 18. 08:04
반응형

Angularjs 동적 ng- 패턴 유효성 검사


확인란이 거짓이면 ng-required 지시문을 사용하여 텍스트 입력에 대한 유효성 검사를 시행하는 양식이 있습니다. 확인란이 true이면 필드가 숨겨지고 ng-required가 false로 설정됩니다.

문제는 ng-pattern 각도 지시문을 사용하여 입력에 지정된 유효성 검사를위한 정규식도 있다는 것입니다. 내가 겪고있는 문제는 사용자가 잘못된 전화 번호를 입력하고 해당 입력을 비활성화하는 확인란을 선택하면 (결과적으로 추가 유효성 검사가 필요하지 않음) 양식이 ng-pattern을 기반으로 유효하지 않기 때문에 제출을 허용하지 않는다는 것입니다.

입력 모델을 null로 설정하는 ng-change 함수를 추가하여이 문제를 해결하려고 시도했지만 ng-pattern이므로 필드는 여전히 확인란의 초기 설정에서 유효하지 않은 것으로 설정되어 있습니다. 그러나 상자를 선택 취소하고 모든 것을 초기 양식로드로 설정 한 다음 상자를 다시 선택하면 양식이 유효하고 제출할 수 있습니다. 내가 무엇을 놓치고 있는지 잘 모르겠습니다. 지금까지 내가 가지고있는 ng-change 코드는 다음과 같습니다.

    var phoneNumberRegex = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    $scope.phoneNumberPattern = phoneNumberRegex;
    $scope.removeValidation = function() {
        if ($scope.cell._newUser === false) {
            $scope.request._number = '';
            $scope.phoneNumberPattern = /[0-9a-zA-Z]?/;
        } else {
            $scope.phoneNumberPattern = phoneNumberRegex;
        }
    };

이것은 흥미로운 문제입니다. 복잡한 Angular 유효성 검사입니다. 다음 바이올린은 원하는 것을 구현합니다.

http://jsfiddle.net/2G8gA/1/

세부

나는 새로운 지침 작성, rpattern각도의의 혼합이다, ng-requiredng-pattern에서 코드를 input[type=text]. 그것이하는 일은 required필드 속성을 관찰하고 regexp로 검증 할 때이를 고려하는 것입니다. 즉, 필수가 아닌 경우 필드를 valid-pattern.

노트

  • 대부분의 코드는 Angular에서 가져 왔으며 이에 맞게 조정되었습니다.
  • 확인란을 선택하면 필드가 필요합니다.
  • 필수 확인란이 false이면 필드가 숨겨지지 않습니다.
  • 데모를 위해 정규식이 단순화되었습니다 (유효한 3 자리).

더러운 새 지침을 원하지 않는 경우 (그러나 작은) 솔루션은 다음과 같을 것이다 :

$scope.phoneNumberPattern = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            if( $scope.requireTel === false ) {
                return true;
            }
            return regexp.test(value);
        }
    };
})();

그리고 HTML에서는 변경이 필요하지 않습니다.

<input type="text" ng-model="..." ng-required="requireTel"
    ng-pattern="phoneNumberPattern" />

This actually tricks angular into calling our test() method, instead of RegExp.test(), that takes the required into account.


Not taking anything away from Nikos' awesome answer, perhaps you can do this more simply:

<form name="telForm">
  <input name="cb" type='checkbox' data-ng-modal='requireTel'>
  <input name="tel" type="text" ng-model="..." ng-if='requireTel' ng-pattern="phoneNumberPattern" required/>
  <button type="submit" ng-disabled="telForm.$invalid || telForm.$pristine">Submit</button>
</form>

Pay attention to the second input: We can use an ng-if to control rendering and validation in forms. If the requireTel variable is unset, the second input would not only be hidden, but not rendered at all, thus the form will pass validation and the button will become enabled, and you'll get what you need.


Used pattern :

 ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"

Used reference file:

 '<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>'

Example for Input:

 <input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">


I just ran into this the other day.

What I did, which seems easier than the above, is to set the pattern on a variable on the scope and refer to it in ng-pattern in the view.

When "the checkbox is unchecked" I simply set the regex value to /.*/ on the onChanged callback (if going to unchecked). ng-pattern picks that change up and says "OK, your value is fine". Form is now valid. I would also remove the bad data from the field so you don't have an apparent bad phone # sitting there.

I had additional issues around ng-required, and did the same thing. Worked like a charm.


Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.

It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test function and validation not working.

Example from Angular docs works good for me:

Modifying built-in validators

html

<form name="form" class="css-form" novalidate>
  <div>
   Overwritten Email:
   <input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
   <span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
   Model: {{myEmail}}
  </div>
</form>

js

var app = angular.module('form-example-modify-validators', []);

app.directive('overwriteEmail', function() {
    var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;

    return {
        require: 'ngModel',
        restrict: '',
        link: function(scope, elm, attrs, ctrl) {
            // only apply the validator if ngModel is present and Angular has added the email validator
            if (ctrl && ctrl.$validators.email) {

                // this will overwrite the default Angular email validator
                ctrl.$validators.email = function(modelValue) {
                    return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
                };
             }
         }
     };
 });

Plunker


You can use site https://regex101.com/ for building your own specific pattern for some country:

For example, Poland:

-pattern = xxxxxxxxx OR xxx-xxx-xxx OR xxx xxx xxx 
-regexp ="^\d{9}|^\d{3}-\d{3}-\d{3}|^\d{3}\s\d{3}\s\d{3}"

참고URL : https://stackoverflow.com/questions/18900308/angularjs-dynamic-ng-pattern-validation

반응형