简体   繁体   中英

The original state of using Angular.js to validate form input

the code below is part of signin.html. when i visit that page, nick and password is surely empty, so the myForm.nick.$error.required is true . the error message is displayed. What i want is, when i visited the page, there's no error message on the page. What should i do? Thanks

<form ng-submit="signin()" name="myForm">
  <input type="text" name="nick" ng-model="data.nick" required>
  <span class="error" ng-show="myForm.nick.$error.required">Required</span><br>
  <input type="password" name="password" ng-model="data.password" required>
  <span class="error" ng-show="myForm.password.$error.required">Required</span><br>
</form>

You should add a $dirty condition to prevent the required field message being displayed at the beginning of page.

myForm.nick.$error.required && myForm.nick.$dirty
myForm.password.$error.required && myForm.password.$dirty

$dirty===true means that user has already interacted with the form.

Here is a jsfiddle demo

Hope this helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM