Search code examples
angularjsangularjs-validation

Why name attribute required in AngullarJs validation


Friends, I am new to angularjs please explain why name attribute required for angularjs validation

<form  name="lform" novalidate>
<input type="text"  name="userName" ng-model="userName" required novalidate/>
<span style="color:red" ng-show="lform.userName.$dirty && lform.userName.$invalid">
<span ng-show="lform.userName.$error.required">Username is required.</span>
</span>
<br/>
</form>

If I remove name="userName" code not working, please explain this.

Update: If I remove "ng-model" it is not working, but I can change "ngmodel='newName'" is working, please explain this reason also.

Solution

  • This is just how HTML form works, name describe the parameter that will be sent to the server.

    Angular's approach is to extend HTML and its behaviour, instead of inventing the wheel. Angular encapsulates "form" (see ngForm directive) and extend it. Because name is the unique id of an input in a form, it is also the unique id of the input in ngForm's collection.

    ng-model is another directive that bind the value of the input into a variable in the current scope, it doesn't have to hold the same value as name.

    Let's take your example and change ng-model:

    <form  name="lform" novalidate>
    <input type="text"  name="userName" ng-model="object.name" required novalidate/>
    <span style="color:red" ng-show="lform.userName.$dirty && lform.userName.$invalid">
    <span ng-show="lform.userName.$error.required">Username is required.</span>
    </span>
    <br/>
    </form>
    

    The validation will work, but the variable that will be updated in your scope is "object.name".

    To sum it up, lform.userName holds the metadata and object.name will hold the actual data.