没有警报的表单验证 [英] Form Validation without Alerts

查看:74
本文介绍了没有警报的表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种无需使用警报即可验证表单的方法.通常,如果您输入了错误的信息或其他内容,您将在输入框旁边看到红色文本.而且我不想使用Jquery.我在html中包括了红色文本消息的div-namemsg,commentmsg,emailmsg.

I was wondering if there's a way to validate the form without using alerts. Like usually you would see red text beside the input box if you typed in the wrong information or something. And I don't want to use Jquery. I've included a div for the red text messages in the html - namemsg, commentmsg, emailmsg.

到目前为止,我只收到带有警报的代码. JavaScript:

So far I've only got the code with alerts. JavaScript:

function validateUser()
{
    var x=document.forms["myForm"]["email"].value;
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length)
    {
        alert("Not a valid e-mail address");
        return false;
    }

    {
        alert("Valid Input");
    }

    return true;
}

HTML

 <form name="myForm" method="post">
    <label>*Name:</label>
    <input type="text" name="name" title="Enter a your name" placeholder="Your Name" onclick="select()" required/>
    <div id="namemsg"></div><br/>

    <label>*E-mail:</label>
    <input type="text" name="email" title="Enter a valid email address" placeholder="me@example.com" onclick="select()" required/>
    <div id="emailmsg">  </div><br/>

    <label>*Comment:</label>
    <textarea name="comment" title="Enter your comments" placeholder="Enter your comments." onclick="select()" required/></textarea>
    <div id="commentmsg">  </div>
    <label id="error"> </label> <br/>
    <input type="submit" value="Submit" onclick="return validateUser()"> 
</form>

推荐答案

您可以将span/label放在具有预定义文本和样式且显示样式为none的经过验证的字段旁边.如果验证检测到无效输入-将显示样式更改为"以使标签可见.

You can place a span/label next to validated field with predefined text and style and display style of none. If validation detects an invalid input - change the display style to "" to make the label visible.

更新

我确实看到您已经预定义了DIV.将其定义为

I do see you have already predefined DIV. Define it as

<div id="emailmsg" style="color:Red;display:none">Not a valid e-mail address</div>

用JavaScript代替

And in JavaScript instead of

alert("Not a valid e-mail address");

使用

document.getElementById("emailmsg").style.display=""

这篇关于没有警报的表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆