HTML/Javascript:提交时的简单表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16134733/
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-08-29 07:43:54  来源:igfitidea点击:

HTML/Javascript: Simple form validation on submit

javascripthtmlformsvalidation

提问by Eduardo Go

I'm trying to validate my form with the easiest way possible, but somehow is not working and when I click submit it just takes me to the next page without giving the alert message:

我正在尝试以最简单的方式验证我的表单,但不知何故不起作用,当我单击提交时,它只会将我带到下一页而没有给出警报消息:

HTML:

HTML:

<form name="ff1" method="post" onsubmit="validateForm();">
 <input type="text" name="email" id="fremail" placeholder="[email protected]" />
 <input type="text" name="title" id="frtitle" placeholder="Title" />
 <input type="text" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
 <input type="submit" name="Submit" value="Continue" />         
</form>

Javascript:

Javascript:

<script type="text/JavaScript">

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return re.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) { } else {
        alert("Please enter only alphanumeric values for your advertisement title");
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
    }
  return false;
}
</script>

Here is also in jsfiddle http://jsfiddle.net/CrLsR/

这里也在 jsfiddle http://jsfiddle.net/CrLsR/

Thanks in advance

提前致谢

回答by Adidi

You have several errors there. first you have to return value from the function in the html markup: <form name="ff1" method="post" onsubmit="return validateForm();">

你有几个错误。首先,您必须从 html 标记中的函数返回值:<form name="ff1" method="post" onsubmit="return validateForm();">

second in jsfiddle your place the code inside onLoad which then the form won't recognize - and last you have to return true from the function if all validation success - I fixed some issues in the update:

在 jsfiddle 中的第二个地方是 onLoad 中的代码,然后表单将无法识别 - 如果所有验证成功,最后你必须从函数返回 true - 我在更新中修复了一些问题:

https://jsfiddle.net/mj68cq0b/

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

回答by Niet the Dark Absol

The simplest validation is as follows:

最简单的验证如下:

<form name="ff1" method="post">
  <input type="email" name="email" id="fremail" placeholder="[email protected]" />
  <input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
  <input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
  <input type="submit" name="Submit" value="Continue" />         
</form>

It uses HTML5 Attributes(like as pattern)

它使用HTML5 属性(如 as pattern

Javascript: none.

Javascript:无。

回答by Jensd

You need to return the validating function. Something like:

您需要返回验证函数。就像是:

onsubmit="return validateForm();"

Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.

然后验证函数应该在错误时返回 false。如果一切正常,则返回 true。请记住,服务器也必须进行验证。

回答by Marcus

Disclosure: I wrote FieldVal.

披露:我写了 FieldVal。

Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.

这是使用FieldVal的解决方案。通过使用 FieldVal UI 构建表单,然后使用 FieldVal 验证输入,您可以将错误直接传递回表单。

You can even run the validation code on the backend (if you're using Node) and show the error in the form without wiring all of the fields up manually.

您甚至可以在后端运行验证代码(如果您使用 Node)并在表单中显示错误,而无需手动连接所有字段。

Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx

现场演示:http: //codepen.io/MarcusLongmuir/pen/WbOydx

function validate_form(data) {
    //This would work on the back end too (if you're using Node)

    //Validate the provided data
    var validator = new FieldVal(data);
    validator.get("email", BasicVal.email(true));
    validator.get("title", BasicVal.string(true));
    validator.get("url", BasicVal.url(true));
    return validator.end();
}


$(document).ready(function(){

    //Create a form and add some fields
    var form = new FVForm()
    .add_field("email", new FVTextField("Email"))
    .add_field("title", new FVTextField("Title"))
    .add_field("url", new FVTextField("URL"))
    .on_submit(function(value){

        //Clear the existing errors
        form.clear_errors();

        //Use the function above to validate the input
        var error = validate_form(value);

        if (error) {
            //Pass the error into the form
            form.error(error);
        } else {
            //Use the data here
            alert(JSON.stringify(value));
        }
    })

    form.element.append(
        $("<button/>").text("Submit")
    ).appendTo("body");

    //Pre-populate the form
    form.val({
        "email": "[email protected]",
        "title": "Your Title",
        "url": "http://www.example.com"
    })
});

回答by Naim Serin

HTML Form Element Validation
Run Function

HTML 表单元素验证
运行函数

<script>
           $("#validationForm").validation({
                button: "#btnGonder",
                onSubmit: function () {
                    alert("Submit Process");
                },
                onCompleted: function () {
                    alert("onCompleted");
                },
                onError: function () {
                    alert("Error Process");
                }
           });
</script>

Go to example and download https://github.com/naimserin/Validation

转到示例并下载https://github.com/naimserin/Validation

回答by Nizar B.

I use this really simple small JavaScript library to validate a complete form in one single line of code:

我使用这个非常简单的小型 JavaScript 库在一行代码中验证一个完整的表单:

 jsFormValidator.App.create().Validator.applyRules('Login');

Check here: jsFormValidator

在这里检查:jsFormValidator

The benefit of this tool is that you just write a JSON object witch describe your validation rules, no need to put line like:

这个工具的好处是你只需编写一个 JSON 对象来描述你的验证规则,不需要像这样放置一行:

 <input type=text name="username" data-validate placeholder="Username">

data-validate is injected in all the input fields of your form but when using jsFormValidator, you don't require this heavy syntax and the validation will be applied to your form in one shot, without need to touch at your HTML code.

data-validate 注入到表单的所有输入字段中,但是当使用 jsFormValidator 时,您不需要这种繁重的语法,验证将一次性应用于您的表单,而无需触摸您的 HTML 代码。