Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix HTML5 and custom angularjs validation

Tags:

html

angularjs

Given following input field:

<input type="text" class="form-control" data-ng-model="selectedUser.userName" data-ng-hide="selectedUser.uuid" required name="userName">

The required tag will have the browser show a nice error when the form is submitted if the user did not enter a value. However, I want to do some additional validation on this field: when creating a new user the userName must not exist already.

Doing the actual validation with angular is quite straightforward:

$scope.submit = function() {

    userService.getByUserName($scope.selectedUser.userName, function(data) {
        if (!data) {
            $scope.userForm.userName.$setValidity("unique", false);
        }
    });

    if ($scope.userForm.$invalid) {
        return;
    }
    ...
}

How do I go about to show a HTML5 validation error in this case?

It seems the common way with angular is to have a custom error message like this:

<span style="color:red" ng-show="userForm.userName.$error.unique">We have met before...</span>

But then I would end up with 2 different styles of error messages which I do not want.

How do I leverage the HTML5 setCustomValidity() functionality (allowing you to set a custom error message for HTML5 validation) in angular?

like image 894
Stijn Geukens Avatar asked Jul 26 '26 22:07

Stijn Geukens


1 Answers

You can remove the HTML5 validation by adding novalidate attribute.

<input type="text" class="form-control" data-ng-model="selectedUser.userName" data-ng-hide="selectedUser.uuid" required name="userName" novalidate>
like image 55
Tome Pejoski Avatar answered Jul 29 '26 13:07

Tome Pejoski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!