3

I have one AngularJS application. I have a registration page.

looks like this

register.html

<form id="userRegistration" ng-submit="registerUser()" >
<fieldset>
    <label class="block clearfix">
        <span class="block">
            <input type="text" class="form-control" id="Username" ng-model="user.username" name="username" placeholder="Username" required="required" />
        </span>
    </label>

    <label class="block clearfix">
        <span class="block">
            <input type="password" class="form-control" id="password" ng-model="user.password" name="password" placeholder="Password" required="required" />
        </span>
    </label>

    <label class="block clearfix">
        <span class="block">
            <input type="email" class="form-control" id="email" ng-model="user.email" name="emailId" placeholder="Email" required="required" />
        </span>
    </label>
    <div class="clearfix">
        <button type="reset" class="width-48 pull-left btn btn-sm">
            Reset
        </button>

        <button type="submit" class="width-48 pull-right btn btn-sm btn-success">
            Register
        </button>
    </div>
</fieldset>

I am using this wraspbootstrap theme. It has form validations. That validation I am using. I have given my rules in page itself.

$( document ).ready(function() {
    $.mask.definitions['~']='[+-]';
    $('#phone').mask('(999) 999-9999');

    jQuery.validator.addMethod("phone", function (value, element) {
        return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
    }, "Enter a valid phone number.");

    $('#userRegistration').validate({
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        rules: {
            userName:{
                required: true,
            },
            password: {
                required: true,
                minlength: 5
            },
            emailId: {
                required: true,
                email:true
            }
        },

        messages: {
            userName:{
                required:"Please choose a user name."
            },
            password: {
                required: "Please specify a password.",
                minlength: "Please specify a password of atleast 5 character."
            },
            emailId: {
                required: "Please provide email.",
                email: "Please provide a valid email."
            }
        },

        invalidHandler: function (event, validator) { //display error alert on form submit   
            $('.alert-danger', $('.login-form')).show();
        },

        highlight: function (e) {
            $(e).closest('label.block').addClass('has-error');
        },

        success: function (e) {
            $(e).closest('label.block').removeClass('has-error');
            $(e).remove();
        },

        errorPlacement: function (error, element) {
            if(element.is(':checkbox') || element.is(':radio')) {
                var controls = element.closest('div[class*="col-"]');
                if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if(element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if(element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else error.insertAfter(element.parent());
        },

        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    });

});
</script>

When I click on submit button, the Jquery validation is hapening and error messages coming. But at the same time, it is calling registerUser() method in angularJS and posting the user in controller.

This is my controller JS register.js

angular.module('myApp').controller('RegisterController', function($scope,$http) {
    page.setPage("Register","login-layout");
    $scope.user = {};
    $scope.registerUser=function()
    {
       alert("Submitting...");
    }
});

It always alerts the message whenever I click the submit button, even if the form is invalid. The validation happens only if I click on submit button only. So how can I call the method only if the form is valid?

4
  • You need to check the validity again in registerUser method as: if (!$("#userRegistration").valid()) return; Commented Jan 6, 2014 at 11:57
  • Inside my controller? Commented Jan 6, 2014 at 12:01
  • Thanks. Got it. I could accept as answer if it is a comment :) Commented Jan 6, 2014 at 12:04
  • No worries buddy. I'm just glad I could help! Commented Jan 6, 2014 at 12:07

1 Answer 1

9

UPDATE

I found a better way without JQuery. I found this answer long back, but now I remembered to update here after a year. The forms will be available in $scope object. So just give a name to the form and use it.

HTML

<form id="userRegistration" name="registration" ng-submit="registerUser()" >

Controller

$scope.registerUser=function()
    {
       if ($scope.registration.$valid){
           alert("Submitting...");
       }
    }

OLD Answer

Thanks to srvikram for the comment. I am adding the comment as answer here.

angular.module('myApp').controller('RegisterController', function($scope,$http) {
    page.setPage("Register","login-layout");
    $scope.user = {};
    $scope.registerUser=function()
    {
       if ($("#userRegistration").valid()){
           alert("Submitting...");
       }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.