简体   繁体   中英

HTML5 required field but not a 'submit' type of button

I have a field:-

 <div class="row" style="margin-left: 30px">
      <div style="display: inline-block;">
           Name: 
      </div>
      <div style="display: inline-block; margin-left: 28px; width: 383px;">
           <input type="text" data-ng-model="currentUser.Name" required>
      </div>
</div>

The submit button in my form :-

<button data-ng-click="addNew(currentUser)" class="btn btn-primary" type="button">Add New User</button>

is of type=button... that is because I want to avoid a post-back.... However this is causing issues with how the required field is supposed to behave in my HTML5 code.... Does this mean I have to implement custom error checking in Javascript? If so can anyone show my how I can do that, because I alread have a click function defined on my submit button...

You can also use this piece of code:

<form onsubmit="return validate()">
    <div class="row" style="margin-left: 30px">
        <div style="display: inline-block;">Name: </div>
        <div style="display: inline-block; margin-left: 28px; width: 383px;">
            <input type="text" data-ng-model="currentUser.Name" required>
        </div>
    </div>
    <button data-ng-click="addNew(currentUser)" class="btn btn-primary" type="submit">Add New User</button>
</form>

And JavaScript function:

function validate() {
    // validation logic or whatever you want
    return true; // return false; in case of validation error
}

As @dfsq mentioned in comment, novalidate attribute and manual validation on Angular site is preffered way to do it clean and elegant.

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