gpt4 book ai didi

javascript - 文本区域验证不起作用

转载 作者:行者123 更新时间:2023-11-28 07:47:46 25 4
gpt4 key购买 nike

我开发了一个表单来获取用户输入并在文本区域中输入,我想避免用户输入特殊字符。

以下是表单的代码和我用于验证的函数。问题是即使在使用验证之后,它仍然接受用户输入的特殊字符。我找不到出了什么问题。请帮我。

提前致谢

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page language="java" session="true" %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="scripts/scripts.js"></script>

<title>Untitled Document</title>
</head>
<body>
<form name = "MyForm" action="SubmitUser" method ="post" onsubmit="validate()">

<textarea rows="6" cols="150" name="comment" value="">
</textarea>


<input type = "submit" name ="sub" value="Submit">

</body>
</html>

以下是scripts.js

function validate() {
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.MyForm.comment.value.length; i++) {
if (iChars.indexOf(document.MyForm.comment.value.charAt(i)) != -1) {
alert ("This Field has special characters. \nSpecial Characters are not allowed");
return false;
}
}
}

最佳答案

您没有停止表单的提交事件。要停止正常流程,您可以修改以下逻辑代码:

<form name = "MyForm" action="SubmitUser" method ="post">

<textarea rows="6" cols="150" name="comment" value="">
</textarea>


<input type = "button" name ="sub" value="Submit" onclick="validate()">

并将您的 JavaScript 修改为:

function validate(){
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.MyForm.comment.value.length; i++) {
if (iChars.indexOf(document.MyForm.comment.value.charAt(i)) != -1) {
alert ("This Field has special characters. \nSpecial Characters are not allowed");
return false;
}
document.MyForm.submit();
}

希望您有进行验证的逻辑!

关于javascript - 文本区域验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27224968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com