3

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?

1
  • What is the point of trying to use competing API's for the same task? Use one or the other. Best to use angular one since you have far more control over it Commented Jan 25, 2015 at 13:57

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

That's indeed one way to go about it but I would prefer to go the other way if that's possible (so, add custom angularjs validation on top of the HTML5 validation and show all errors in HTML5 style).
Well, since all the browsers implement HTML5 features differently (including validation), I think it's hard to keep the default validation and add something on top of it. If you want to have custom validation, the best practice is to disable HTML5 validation and handle it all by yourself.
It is a bit of a shame to have all these nice HTML5 features and not being able to use them.
@StijnGeukens I get where you are coming from. I had the same issue a couple of days ago. At least you can still use html5 attributes

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.