【发布时间】:2015-05-07 02:02:49
【问题描述】:
我是 asp.net mvc 的新手,我有一个带有一些验证的表单,我想在客户端验证它,所以我用 javascript 编写普通脚本 更具体地说,我的问题是返回 false (因为它不应该向服务器发送任何数据并且仍然在 apage 中,但这不会发生),注意:我用 js 在普通 html 文件中测试脚本并且工作正常 但正如我所说,我对 mvc 不熟悉,所以我想知道我是否错过了在其中工作的任何东西,以及在这个特定点是否有任何 toturial 参考,这会很好,正如我在这个地方注意到的那样(没有适合初学者的地方:); 这也是我的代码的 sn-p
@model registerationex.Models.register
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
<fieldset>
<legend>register</legend>
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
<span id="error"></span>
@Html.ValidationMessageFor(model => model.name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.email)
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="The email field is required." id="email" name="email" type="text" value="" onblur="checkuser(email);">
<span id="erroruser"></span>
@Html.ValidationMessageFor(model => model.email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.age)
<span id="errorage"></span>
@Html.ValidationMessageFor(model => model.age)
</div>
<p>
<input type="submit" value="Create" onclick="allvalidate();" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<script>
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(age)) validated = false;
if (!checkuser(email)) validated = false;
return validated;
}
function validate() {
var txtf = document.getElementById('name');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
</script>
【问题讨论】:
标签: javascript c# asp.net asp.net-mvc asp.net-mvc-4