asp.net mvc中的表单验证(使用javascript)

时间:2015-05-07 02:02:49

标签: javascript c# asp.net asp.net-mvc asp.net-mvc-4

我是asp.net mvc的新手,我有一些验证,我想在客户端验证它,所以我在javascript写正常的脚本 更多的specefic我的问题是返回false(因为它不应该向服务器发送任何数据,但仍然在apage但这不会发生),请注意:我用js在普通的html文件中测试脚本并且工作正常 但正如我所说,我不熟悉mvc,所以我想知道是否有任何我错过了工作的东西,如果有任何提及在这个specefic点任何toturial它会很好,因为我注意到在这个地方(初学者没有地方:); 这也是我的代码片段

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

2 个答案:

答案 0 :(得分:3)

您已包含@Scripts.Render("~/bundles/jqueryval"),默认情况下为jquery.validate.unobtrusive.js,因此请删除所有脚本并使用MVC附带的功能。只需将验证属性添加到您的属性中即可。

[Required(ErrorMessage = "you must enter firstname")]
public string name { get; set; }

[EmailAddress(ErrorMessage = "enter valid email")]
public string email { get; set; }

[Required(ErrorMessage = "you must your age")]
[Range(18, 70, ErrorMessage = "age must be from 18 : 70")]
public int age { get; set; }

现在,您的脚本尝试执行的所有操作(严重错误)都是开箱即用的(假设您没有禁用不显眼的验证),并且在纠正错误之前表单不会提交。您现在还获得服务器端验证,这是必不可少的验证(客户端验证只是一个很好的奖励,但任何人都可以轻松通过它),因此您必须始终在服务器上验证

同时替换您手动尝试使用@Html.EditorFor(m => m.email)为电子邮件属性创建输入并删除所有onclick attibutes

附注:你的正则表达式^[a-zA-Z]+$甚至不允许输入有效的电子邮件地址(它甚至不允许@.个字符!)。使用EmailAddress]属性将生成正确的正则表达式(来自jQuery Validation 1.9.0

^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$

答案 1 :(得分:0)

allvalidate()函数应该如下所示(调用提交函数,而不是返回值):

<script>
        function allvalidate() {
            var validated = true;
            if (!validate()) validated = false;
            if (!checkAge(age)) validated = false;
            if (!checkuser(email)) validated = false;

            if(validated)
                $('[type="submit"]').submit();
        }
   </script>