Form Validation without Alerts - javascript

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>

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
<div id="emailmsg" style="color:Red;display:none">Not a valid e-mail address</div>
And in JavaScript instead of
alert("Not a valid e-mail address");
Use
document.getElementById("emailmsg").style.display=""

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:
alert("Not a valid e-mail address");
With:
document.forms["myForm"]["email"].style.border = "1px solid red";
document.getElementById("emailmsg").innerHTML = "Not a valid e-mail address";
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:
<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/>
// this span is hidden until you show it as error msg
<span id="error" style='display: none'>Not a valid e-mail address<span>
<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>
your js:
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)
{
//instead of alerting error show your error span try to put nice css for it
document.getElementById('error').style.display="block";
return false;
}
{alert("Valid Input");}
return true;
}

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...";

This should help.
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length){
// validate message function call
valMessage('emailmsg', 'Not a valid e-mail address');
return false;
}
// validate message function
function valMessage(divName, content) {
document.getElementById(divName).innerHTML = content;
}

Related

For Javascript in HTML Form Still Submits Despite Breaking Requirements

So essentially my problem is that I am trying to make a form where certain rules need to be met, like the password should have an uppercase and you need to confirm your password, but despite failing the validation the form will still submit. The only validation that works is the default requirement that the text box needs to have something written in it. How would I go about making it so the validation actually stops the form from going through.
The code I currently have works in that it will return true/false depending on if it passes, its just that even if it does not pass the form will still go through. I know I probably need a event.preventDefault() somehwhere but I don't know where.
<form class="w3-container w3-margin" name="login" action="loginAction.jsp">
<h1>Create a Username and Password</h1>
<!-- These divs are the text fields for information the user needs to give the website -->
<div class="w3-section">
<label>Username</label>
<input class="w3-input w3-border" type="text" placeholder="Name" name="username" size="20" required>
</div>
<div class="w3-section">
<label>Email</label>
<input class="w3-input w3-border" type="text" placeholder="Email" name="email" required>
</div>
<!-- For the password the method validPassword() is used which checks if the password has an uppercase -->
<div class="w3-section">
<label>Password (Must have at least one upper case)</label>
<input class="w3-input w3-border" type="text" placeholder="Password" name="password" onInput="validPassword()" size="15" required>
</div>
<!-- For confirm password the method matchingPasswords() is used which checks if the two typed passwords are the same -->
<div class="w3-section">
<label>Confirm Password</label>
<input class="w3-input w3-border" type="text" placeholder="Confirm Password" name="cpassword" onInput="matchingPasswords()" size="15" required>
</div>
<!--These are submit and reset buttons -->
<div class="w3-section">
<input class="w3-button topbotColor" type="submit" value="Button" />
<input class="w3-button topbotColor" type="reset" value="Reset" />
</div>
</form>
This is the javascript code.
//function validPassword is meant to check if the password has a uppercase letter
function validPassword() {
//var password stores the password element from the text box
var password = document.getElementsByName("password");
//var ucletters is the set of all capital letters
var ucletters = /^(?=.*[A-Z]).+$/;
//If there is at least one uppercase in the password text
if(ucletters.test(password[0].value)){
//Pass validity and return true
document.getElementsByName("password").setCustomValidity("");
return true;
}
else {
//else the password does not have an uppercase
document.getElementByName.setCustomValidity("This password does not fit criteria");
return false;
}
}
//matchingPasswords is meant to check if two passwords were the same
function matchingPasswords() {
//password stores the text in the password text box
var password = document.getElementsByName("password");
//cpassword stores the text in the confirm password text box
var cpassword = document.getElementsByName("cpassword");
//If the string in password does not match the string in confirm password
if (password[0].value !== cpassword[0].value) {
//it fails validity and should return false
document.getElementsByName("cpassword").setCustomValidity("Emails do not match");
return false;
}
else {
//else it passes and should be true
document.getElementsByName("cpassword").setCustomValidity("");
return true;
}
}
/*function completeForm() {
if (validPassword() !== true && matchingPasswords() !== true){
event.preventDefault();
}
}*/
1.) Remove the forms action value
2.) Add Event Listeners for your code to run(I don't see how any functions are running)
document.getElementById("your_submit_button").addEventListener('click', function_you_want_to_run);
3.) Use this code to redirect the client to your form action
window.location.url="/link.jsp";

Javascript Form Validation (phone)

I have a form which has name, email and content text area. It all works fine but when I'm trying to add 1 more form input for mobile phone numbers the form wont submit.
Javascript:
function hgsubmit() {
if (/\S+/.test(document.hgmailer.name.value) == false)
alert("Please provide your name.");
else if (/^\S+#[a-z0-9_.-]+\.[a-z]{2,6}$/i.test(document.hgmailer.email.value) == false)
alert("A valid email address is required.");
else if (/\S+/.test(document.hgmailer.comment.value) == false)
alert ("Your email content is needed.");
else {
document.hgmailer.submit();
alert ('Thank you!\nYour email is sent.');
}
}
HTML:
<form action="http://www.jim123code.com/cgi-sys/formmail.pl" method="post"
name="hgmailer">
<input type="hidden" name="recipient" value="info#jim123code.com">
<input type="hidden" name="subject" value="Form E-Mail">
Contact Form
<br>
<br>
Visitor Name: <input type="text" name="name" size="30" value="">
<br>
Visitor E-Mail: <input type="text" name="email" size="30" value="">
<br>
E-Mail Content: <textarea name="comment" cols="50" rows="5"></textarea>
<br>
<br>
<input type="button" value="E-Mail Me!" onclick="hgsubmit();">
<input type="hidden" name="redirect" value="http://www.jim123code.com/">
</form>
The code for the form above is the approved contact form that works with my webhosting provider (ehost). Now i've tried adding a mobile phone number input by copying and pasting the other input types and changing a few things around but no luck. please advise the best way to add a phone number input + the javascript validation code for it to all work together.
For a new input to be sent, be sure to include it inside the form tag and add a unique value for the name property.
Example:
<input type="text" name="phoneNumber" size="10" value="">
For more information about forms check HTML Forms.
You are gonna have to create a custom formmail script to handle your new form. If you know perl you can try modifying the existing script. Otherwise tough nuggies.

How to validate an input type="text" element to only accept certain content?

I have a text input field:
<input type="text" name="email" size="25" placeholder="Email Address" required/>
Is there a way to format the input field to only allow certain text to be valid?
For example: In that particular text field, the user must input an email address which ends in #hotmail.co.uk. Any other email domains such as #yahoo.com will not be valid and therefore will show an error when clicking submit (Will not register the user).
You can use the HTML5 pattern attribute to validate whether the string ends with #hotmail.co.uk.
In this case you can use the following regular expression:
^.*#hotmail\.co\.uk$
<form>
<input type="text" name="email" pattern="^.*#hotmail\.co\.uk$" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>
Alternatively, you could also just attach an input event listener to the element and check manually. This is just a basic example, feel free to customize to your needs. I would still suggest validating that the value is a valid email address by using the regex from this question.
$('input[name="email"]').on('input', function(e) {
var isValid = this.value.match(/^.*#hotmail\.co\.uk$/) !== null;
$(this).toggleClass('isValid', isValid);
});
.isValid {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>
many solutions are available:
validate form with javascript.
use 2 inputs: a text input for the username and a select options or radio buttons for "#site.com"
pattern attribute on input
Extended answer using the "pattern" attribute (from Josh Crozier):
After the user changed the value of the input you can check it for a valid input:
In addition you could test the input while the user is typing the value and highlight the border:
function check(el) {
if (new RegExp(el.pattern).test(el.value) == false) {
alert("Bad Input")
}
}
function test(el) {
if (new RegExp(el.pattern).test(el.value) == false) {
el.classList.add("bad")
} else {
el.classList.remove("bad")
}
}
.bad {
border-color: red;
}
<input pattern="^.*#hotmail\.co\.uk$" onchange="check(this)" oninput="test(this)" type="text" name="email" size="25" placeholder="Email Address" required/>

How can i change AlertBox into a div?

I would like to know how can I change the AlertBox into a div.
I want the alertBox message to appear next to the input but in a div.
Thank You.
This is my Form input code:
<form name="form" action="gigi.php" method="POST" onsubmit="return validateForm()">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="name" type="text" size="30"/><br>
Last Name:<br />
<input name="lname" type="text" size="30"/><br>
Email:<br>
<input name="caca" type="text" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input class="submit" type="submit" value="Send email"/>
</form>
And this is First Name input code in JavaScript:
function validateForm(){
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
In your HTML add something like:
<div id="form-errors"></div>
Then in JS, you can do that:
var alertDiv = document.getElementById('form-errors');
if (!x || x == '') {
alertDiv.textContent = 'First name must be filled out!';
}
Readings:
textContent
Similar question
Your question is about forms ? Since HTML5 you can simply write required on the input tab and it won't validate until you write some data.. you can then sanitize it.
In addition to Ramy's response, you can add jquery hide/show effects to display and hide the div element.
Also, do not forget to add style "z-index" to the div, so that it will appear on above other content of web-page.

Javascript form validation not working - Script not being called?

I have a pretty straight-forward javascript form validation script written:
function validateForm(){
var x=document.forms["contactForm"]["firstname"].value;
if (x==null || x==""){
return false;
}
var y=document.forms["contactForm"]["lastname"].value;
if (y==null || y==""){
return false;
}
var z=document.forms["contactForm"]["emailaddress"].value;
var atpos=z.indexOf("#");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length){
return false;
}
var msg_area = document.getElementById("message");
msg_area.innerHTML = "";
if (document.getElementById("message").value.length < 20) {
return false;
}
else document.getElementById("contactForm").submit();
}
It's supposed to be validating this form:
<form name="contactForm" onsubmit="return validateForm()" action="./thankyou.html" method="post">
<label for="firstName">First Name <sup>*</sup></label>
<input name ="firstname" id="firstName" type="text" placeholder="First Name" required />
<label for="lastName">Last Name <sup>*</sup></label>
<input name ="lastname" id="lastName" type="text" name="lastName" placeholder="Last Name" required />
<label for="emailaddress">Email address <sup>*</sup></label>
<input name="emailaddress" id="emailAddress" type="email" placeholder="something#example.com" required />
<label for="message">Message<sup>*</sup></label>
<textarea id="message" placeholder="Remember, be nice!" required></textarea>
<input type="submit" name="submit" value="Email Me!" class="emailsub" />
<p class="small"><sup>*</sup> denotes a required field.</p>
</form>
When it's submitted, it doesn't seem to actually call the javascript at all. The only thing that it looks for is that it meets the "required" part of the html. I'm pretty new to javascript so it's probably glaringly obvious where the problem is, but I just can't locate it myself.
Any help is much appreciated!
p.s. this is for a local website at the moment so the action="" goes to another html instead of a page to process the message. Is this possibly the problem here?
The html5 "required" attribute tells the browser to validate before proceeding, read more here. This means that it's stopping the event before the javascript function is even called (on supported browsers) unless it passes the basic validation (required fields and email).
If you want the javascript to execute and perform your own validation, you'll need to remove the "required" attribute. You may also try more complex html form validation. Here is a good article on the subject.

Categories

Resources