我必须使用名称,年龄或电子邮件等字段制作一个小表格。例如:
<input id="name" type="text" required/>
我的验证有问题,因为我想使用html的自动验证来检查所有带有所需标记的字段是否为空,然后使用javascript验证某些字段(如电子邮件) 。我有一个这样的提交输入元素:
<input type="submit" value="Submit" onclick="form.validate()" />
问题是onclick方法(validate())总是在自动验证之前被调用,而我想要做的是在自动验证结束后调用该方法(并且它的一切正确)。我用来测试的javascript看起来像这样:
"use strict";
class Form {
constructor(){}
validate(){
alert("validate");
}
}
var form = new Form();
始终显示警报,但自动验证不会显示。如果我没有将onclick标签及其方法放在提交按钮上,则自动验证有效。对我的问题有任何想法吗?
答案 0 :(得分:0)
您需要在表单中使用指令ng-submit
:
<form ng-submit="form.validate()" ng-controller="YourController">
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
https://docs.angularjs.org/api/ng/directive/ngSubmit https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action
继续摇滚!
答案 1 :(得分:0)
此方法使用jQuery。首先,您需要阻止表单提交上的默认操作,然后您可以进行验证,然后最终提交表单。示例如下。
您的表格:
<form id="form">
<input type="text" required>
<input type="submit" value="Submit!">
</form>
Javascript(使用jQuery):
$('#form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
form.validate();
alert('here');
this.submit(); // If all the validations succeeded
});
的JavaScript(香草):
document.getElementById('form').addEventListener('submit', function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
alert('here');
this.submit(); // If all the validations succeeded
});