Programing

입력 유효성 검사가 실패 할 때 Angularjs가 양식 제출을 방지

lottogame 2020. 6. 9. 07:35
반응형

입력 유효성 검사가 실패 할 때 Angularjs가 양식 제출을 방지


클라이언트 측 입력 유효성 검사와 함께 angularjs를 사용하여 간단한 로그인 양식을 작성하여 사용자 이름과 암호가 비어 있지 않고 3 자보다 길지 않은지 확인하고 있습니다. 아래 코드를 참조하십시오 :

<form name="loginform" novalidate ng-submit="login.submit()" class="css-form">
    <fieldset>

        <div class="control-group input-prepend">
            <span class="add-on"><i class="icon-user"></i></span>
            <input type="text" ng-model="login.username" name="username" required ng-minlength="3" placeholder="username" />
        </div>

        <div class="control-group input-prepend">
            <span class="add-on"><i class="icon-lock"></i></span>
            <input type="password" ng-model="login.password" name="password" required ng-minlength="3" placeholder="" />
        </div>

        <div class="control-group">
            <input class="btn" type="submit" value="Log in">
        </div>

    </fieldset>
</form>

그리고 컨트롤러 :

var controller = function($scope) {

    $scope.login = {
        submit: function() {

            Console.info($scope.login.username + ' ' + $scope.login.password);
        }
    }

};

문제는 login.submit입력이 유효하지 않더라도 함수가 호출 된다는 것입니다. 이 행동을 막을 수 있습니까?

부수적으로 부트 스트랩과 requirejs를 사용한다고 언급 할 수 있습니다.


넌 할 수있어:

<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">

컨트롤러 점검이 필요 없습니다.


제출 단추를 다음으로 변경하십시오.

<button type="submit" ng-disabled="loginform.$invalid">Login</button>

따라서 TheHippo의 제안 된 답변이 저에게 효과적이지 않은 대신 양식을 매개 변수로 함수에 다음과 같이 전송했습니다.

<form name="loginform" novalidate ng-submit="login.submit(loginForm)" class="css-form">

이렇게하면 컨트롤러 방식에서 양식을 사용할 수 있습니다.

$scope.login = {
    submit : function(form) {
        if(form.$valid)....
    }

양식은 자동으로 $ scope에 객체로 배치됩니다. 그것은 통해 액세스 할 수 있습니다$scope[formName]

아래는 ng-submit에서 매개 변수로 양식 자체를 전달하지 않고 원래 설정에서 작동하는 예제입니다.

var controller = function($scope) {

    $scope.login = {
        submit: function() {
            if($scope.loginform.$invalid) return false;

        }
    }

};

작업 예 : http://plnkr.co/edit/BEWnrP?p=preview


HTML :

<div class="control-group">
    <input class="btn" type="submit" value="Log in" ng-click="login.onSubmit($event)">
</div>

컨트롤러에서 :

$scope.login = {
    onSubmit: function(event) {
        if (dataIsntValid) {
            displayErrors();
            event.preventDefault();
        }
        else {
            submitData();
        }
    }
}

OPs 질문에 대한 직접적인 해결책은 아니지만 양식이 ng-app컨텍스트 내에 있지만 Angular가 완전히 무시하기를 원하는 경우 ngNonBindable지시문을 사용하여 명시 적으로 수행 할 수 있습니다 .

<form ng-non-bindable>
  ...
</form>

위의 답변에 추가하면

아래와 같이 2 개의 일반 버튼이 있습니다. (어딘가에 type = "submit"없음)

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

아무리 시도해도 양식이 유효하면 Enter 키를 누르면 "양식 지우기"단추가 호출되어 전체 양식이 지워집니다.

해결 방법으로

I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.

<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>

<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

Well, my intention was never to submit on Enter, so the above given hack just works fine.


I know this is an old thread but I thought I'd also make a contribution. My solution being similar to the post already marked as an answer. Some inline JavaScript checks does the trick.

ng-click="form.$invalid ? alert('Please correct the form') : saveTask(task)"

I know it's late and was answered, but I'd like to share the neat stuff I made. I created an ng-validate directive that hooks the onsubmit of the form, then it issues prevent-default if the $eval is false:

app.directive('ngValidate', function() {
  return function(scope, element, attrs) {
    if (!element.is('form'))
        throw new Error("ng-validate must be set on a form elment!");

    element.bind("submit", function(event) {
        if (!scope.$eval(attrs.ngValidate, {'$event': event}))
            event.preventDefault();
        if (!scope.$$phase)
            scope.$digest();            
    });
  };
});

In your html:

<form name="offering" method="post" action="offer" ng-validate="<boolean expression">

참고URL : https://stackoverflow.com/questions/16263158/angularjs-prevent-form-submission-when-input-validation-fails

반응형