programing

입력 상자가 비어 있는지 확인합니다.

mailnote 2023. 3. 12. 11:00
반응형

입력 상자가 비어 있는지 확인합니다.

지정된 입력 컨트롤이 비어 있는지 확인하려면 어떻게 해야 합니까?난 있는 걸 안다.$pristine필드의 속성: 주어진 필드가 처음에 비어 있으면 누군가가 필드를 채우고 전체 내용을 다시 끌어당기면 어떻게 됩니까?

사용자에게 필드가 필수라는 것을 알려주기 위해서는 위의 기능이 필요하다고 생각합니다.

어떤 아이디어라도 감사합니다!

매우 간단합니다.

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

또,ng-hide="somefield.length"대신ng-show="!somefield.length"그게 더 자연스럽게 읽혀진다면요.


더 나은 대안은 Angular의 폼 기능을 활용하는 것일 수 있습니다.

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Plnkr을 업데이트했습니다.

줄의 길이를 재지 않아도 됩니다.! 오퍼레이터가 모든 것을 해결해 드립니다.항상 기억하십시오!(빈 문자열) = true!(일부 문자열) = false

다음과 같이 쓸 수 있습니다.

<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>

또 다른 접근법은 다음과 같이 regex를 사용하는 것입니다.빈 regex 패턴을 사용하여 ng-pattern을 사용하여 같은 것을 실현할 수 있습니다.

HTML:

 <body ng-app="app" ng-controller="formController">
 <form name="myform">
 <input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
 <span ng-show="myform.myfield.$error.pattern">Please enter!</span>
 <span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>

컨트롤러:@formController:

var App = angular.module('app', []);
App.controller('formController', function ($scope) {              
  $scope.mypattern = /^\s*$/g;
});

의 답변은 Angular 6에서는 작동하지 않았습니다.그래서 제가 해결한 방법은 다음과 같습니다.입력 상자를 이렇게 정의했습니다.

<input type="number" id="myTextBox" name="myTextBox"
 [(ngModel)]="response.myTextBox"
            #myTextBox="ngModel">

필드가 비어 있는지 확인하려면 이 스크립트가 필요합니다.

<div *ngIf="!myTextBox.value" style="color:red;">
 Your field is empty
</div>

위의 답변과 이 답변의 미묘한 차이점에 유의하십시오.추가 속성을 추가했습니다..value내 입력 이름 뒤에myTextBox위의 답변이 Angular의 위 버전에서 효과가 있었는지 모르겠지만 Angular 6의 경우 이렇게 해야 합니다.

이 체크가 기능하는 이유에 대한 자세한 설명입니다.입력 상자에 값이 없는 경우 기본값은 다음과 같습니다.myTextBox.value될 것이다undefined텍스트를 입력하는 즉시 텍스트는 새로운 값이 됩니다.myTextBox.value.

수표가 다음일 때!myTextBox.value값이 정의되어 있지 않은지 아닌지를 체크하고 있습니다.이것은 다음과 같습니다.myTextBox.value == undefined.

입력 필드가 비어 있지 않은 경우 확인란을 자동으로 켜려면 다음과 같이 하십시오.

 <md-content>
            <md-checkbox ng-checked="myField.length"> Other </md-checkbox>
            <input  ng-model="myField" placeholder="Please Specify" type="text">
 </md-content>

텍스트 상자가 필수 필드이고 일치하는 정규식 패턴이 있으며 최소 길이와 최대 길이인 경우

Test Box 코드

<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">

추가할 NG 클래스

ng-class="{ 'err' :  myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"

언급URL : https://stackoverflow.com/questions/16691778/check-if-a-input-box-is-empty

반응형