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.
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>
This should help.
First, I would recommend attaching the execute of the function to the event
OnSubmit
.HTML:
<form method="post" name="myForm" onsubmit="return validateUser(this);">
JS:
function validateUser(formObj) {}
Next, the only thing you need to do, is just have some sort of container, and if the function detects an error, just append the error text to it.
At the start of each function call, empty the container.
If you want the error to appear next to the textbox/any input tag, just add a
div
/span
next to each field and append the error to it.document.getElementById("emailmsg").innerHTML = "Not cool...";
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.Update
I do see you have already predefined DIV. Define it as
And in JavaScript instead of
Use
Instead of showing alert message box you can color that textbox borders to red color and show the error beneath it. Like, if you replace the following line of code:
With:
The above code will highlight the borders of email field with red color and show error in emailmsg div.
Hope this can help.
your html:
your js: