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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30090704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:39:16  来源:igfitidea点击:

form validation in asp.net mvc ( using javascript )

javascriptc#asp.netasp.net-mvcasp.net-mvc-4

提问by user4833581

i'm new to asp.net mvc and i have aform with some validation and i want to validate it in client side so i write normal script in javascript to be more specefic my problem was the return false ( as it shouldn't send any data to server and still in apage but this doesn't happen) ,note : i test the script in normal html file with js and works fine but as i said i'm not familiar with mvc so i want to know if there any thing i have missed to work in it and if there any reference to any toturial in this specefic point it would be good , as i noticed in this place ( there's no place for beginners :); this is a snippet of my code too

我是 asp.net mvc 的新手,我有一个带有一些验证的表单,我想在客户端验证它,所以我在 javascript 中编写普通脚本以更加具体我的问题是返回 false(因为它不应该发送任何数据到服务器并且仍然在 apage 中,但这不会发生),注意:我用 js 测试普通 html 文件中的脚本并且工作正常,但正如我所说我不熟悉 mvc 所以我想知道是否有任何事情我错过了在它的工作,如果在这个特定点有任何关于任何 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>

回答by

You have included @Scripts.Render("~/bundles/jqueryval")which by default jquery.validate.unobtrusive.js, so delete all your scripts and make use of the features which come with MVC. Simply add the validation attributes to your properties.

您已@Scripts.Render("~/bundles/jqueryval")默认包含which 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; }

Now everything that your scripts are trying to do (badly) is done out of the box (assuming you have not disabled unobtrusive validation) and the form will not submit until the errors are corrected. You also now get server side validation which is the essential validation (client side validation is just a nice bonus, but anyone can easily by pass it) so you mustalways validate on the server

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

Also replace you manual attempt to create an input for the email property with @Html.EditorFor(m => m.email)and remove all the onclickattibutes

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

Side note: you regex ^[a-zA-Z]+$wont even allow a valid email address to be entered (it does not even allow the @or .characters!). Using the EmailAddress]attribute will generate the correct regex which is (from jQuery Validation 1.9.0)

旁注:您的正则表达式^[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])))$

回答by Edward N

The allvalidate() function should look like this ( call submit function, not return value) :

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>