Is there any way to validate an input in Angularjs without using form?

Asked

Viewed 2,009 times

4

I have a input which I wish to validate via Angularjs. However, this input is not within a form. So, when trying to access the form validation information, I was unsuccessful:

<div class="form-group">
    <input name="nick" type="text" class="form-control" ng-model="username.nick" ng-maxlength="10">
    <span class="help-block" ng-show="nick.$error.maxlength">Máximo permitido é 10</span>
</div>

But if I do it that way, it works:

<form name="formUser">
    <div class="form-group">
        <input name="nick" type="text" class="form-control" ng-model="username.nick" ng-maxlength="10">
        <span class="help-block" ng-show="formUser.nick.$error.maxlength">Máximo permitido é 10</span>
    </div>
</form>

In this specific case, I would like to use the validation similar to the second example, but without form.

Is there any way to validate the angular, without using the form?

  • Tried to use the directive ng-form? See more here http://stackoverflow.com/questions/22098584/angularjs-input-validation-with-no-enclosing-form

  • @abfurlan seems to have just answered this. I have known about this directive for a short time.

  • Truth I just saw.

1 answer

5


What you can do is use the directive ng-form. This way, it could stay like this:

<div class="form-group" ng-form="nick">
    <input name="nick" type="text" class="form-control" ng-model="username.nick" ng-maxlength="10">
    <span class="help-block" ng-show="nick.$error.maxlength">Máximo permitido é 10</span>
</div>

This Directive has all the capabilities of the form with name, however it is more used in sub groups. I’ve seen a lot in form Wizard that has several Steps (steps). So instead of using multiple forms, they use the ng-form in stages requiring validation.

Example

  • What does this directive do? Magic?

  • I don’t know if it’s some mistake in my code, but it looks like you have to have the name where is the ng-form.

  • puts it like this ng-form="nick", which in this case is the name of your form

  • Maybe that was the confusion, Gabriel. My "form" is not nick, because it has no form. Actually, nick is the name o input whose ng-model is equal to username.nick.

  • 1

    Gabriel, tested! That’s right. I’ll set the example here, if you want to put in the answer, feel free to +1

  • 1

    http://jsfiddle.net/ny8eLxr8/78/

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.