HTML5 必填字段,但不是“提交”类型的按钮

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

本文关键字:提交 类型 按钮 字段 HTML5      更新时间:2023-09-26

我有一个字段:-

 <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="button">Add New User</button>

类型=按钮...那是因为我想避免回传....但是,这会导致必填字段在我的 HTML5 代码中的行为方式出现问题。这是否意味着我必须在 Javascript 中实现自定义错误检查?如果是这样,任何人都可以告诉我如何做到这一点,因为我在我的提交按钮上定义了单击功能......

你也可以使用这段代码:

<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>

和JavaScript函数:

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

正如评论中@dfsq提到的,novalidate网站上的属性和手动验证Angular是使其干净优雅的首选方式。