I have a form which I want it to be verified and validated by a try-catch block plus two other functions.
Here is what I have:
HTML:
<h5>Please enter your name below</h5>
<form name="textForm">
<label for="name">First name:</label>
<input type="text" name="fname" id="name">
</form>
<h5>Please enter your e-mail below</h5>
<form name="mailForm">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
</form>
<form action="">
<label for="height">Your height:</label>
<input type="text" placeholder="in centimetres" name="personHeight" id="height" />
<br></br>
<input formaction="mailto:test#gmail.com" onclick="heightCheck();validateTextForm();validateMailForm();" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
<br></br>
<p id="mess"></p>
</form>
JS:
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value;
if (x == "")
throw "enter your height";
if (isNaN(x)) throw "not a number";
if (x > 250)
throw "height is too high";
if (x < 80)
throw "height is too low";
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + ".";
}
}
The thing that i want it to happen is the following: Firstly, it does the form validation but afterwards if its correct, submits as well.
I tried to make it first verify the forms before actually submits but without any success.
While browsing i find out it could be done by either stopPropaganation, preventDefault or return false methods but still have no idea how to make it happen.
I will rep the guys who help me. Thanks in advance!
Fiddle: However in fiddle it doesn't run properly as it should: http://jsfiddle.net/5T9sJ/
You need to change your code according to my editions:
...
<input formaction="mailto:test#gmail.com" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
...
Then make processValidate method to wrap all other validations into it:
$(document).ready(function () {
$('input#submit').click(function (e) {
e.preventDefault();
validateTextForm();
validateMailForm();
heightCheck();
});
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x === null || x === "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value;
if (x === "") throw "enter your height";
if (isNaN(x)) throw "not a number";
if (x > 250) throw "height is too high";
if (x < 80) throw "height is too low";
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + ".";
}
}
});
Explanation:
You have several methods bound on submit input type, so clicking on it will always call form submission.
I added jQuery click handler for this action to prevent the default action of submit button.
I think e.preventDefault() suits here the best.
WORKING DEMO: http://jsfiddle.net/rbegf/
Related
I have a list of valid user. I want that only these user will be able to send post request all other user should be identified as invalid user. I have written javascript code but unable to make invalid user to stop the execution of programs.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
for (i=0; i< eMailList.length; i++){
if(x != eMailList[i]){
alert("Not a valid user");
return false;
}
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
At first if you care about security issues, you shouldnt do it on the javascript side.
See code sample below:
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
if($.inArray(x,eMailList) == -1)
{
alert("Not a valid user");
}
else
{
alert("valid user");
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Link to JsFiddle
There is no need to loop through the array you can just use if(eMailList.indexOf(x) < 0) implemented below. The reason your code would always returns false is because that even if you enter a valid email it is not equal to every other item in the array.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
if(eMailList.indexOf(x) < 0){
alert("Not a valid user");
return false;
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
This is what i need help with!
My project needs a If and else statement for the Age part!
and then send the person who has validated correctly to a new page.. I currently have a page but that is just something that is in my USB
also need to explain how its is validating
Please help
!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
var Age = document.forms["myForm"]["Age"].value;
if (Age == null || Age == "") {
alert("Has to be a number between 1 and 150");
return false;
}
var Email = document.forms["myForm"]["Email"].value;
if (Email == null || Email == "") {
alert("Make sure it is the correct Email format");
return false;
}
var myCheck = document.getElementById("check1").checked;
if (myCheck == false) {
alert("Have to tick box to proceed");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="file:///G:/Welcome.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="Age">
Email: <input type="text" name="Email">
<br>checkbox: <input type="checkbox" id="check1" name="myCheck"> </br>
<input type="submit" value="click">
</form>
</body>
</html>
You could extend the if clause with the age check.
var age = document.forms["myForm"]["Age"].value;
if (age == "" || age < 1 || age > 150) {
// ^^^^^^^^^^^^^^^^^^^^^^^
alert("Has to be a number between 1 and 150");
return false;
}
I'd parse the value of the form into a number and then I'd check its range:
var age = Number(document.forms["myForm"]["Age"].value) || 0;
if (age < 1 || age > 150) {
alert("Has to be a number between 1 and 150");
return false;
}
Why convert to number and put Number(document.forms["myForm"]["Age"].value) || 0?
The reason is simple: imagine that a malicious user put in your form the value "NaN". If you didn't do this check, the value of age would be NaN and it'd pass your check (NaN < 1 is false and NaN > 150 is false too).
This way, if a user put "NaN" in the form, the guard would transform it into 0, the alert would trigger and the function would return false.
I'm having trouble finding a way to validate my Gender choice action buttons. I've made efforts at doing it by saying that the buttons can't be left null, but it still recognises one button as being null and won't let me continue. I've tried different variations of this like saying both male and female aren't selected then return false but it still won't work for me. I'm beginning to think that the method I'm going about it just may not be correct. The main issue you want to look at the below is the two radio buttons but I have included the rest of the code as context for the Javascript. The rest of the code works fine it is only the radio buttons than I'm struggling with. Thanks.
Html
<form action="ReviewPHP.php" name="review" onsubmit="return validateForm()">
<fieldset>
Title: <input type="text" name="Title">
</br>
Email Address: <input type="text" name="Email">
<br/>
Rating: <select name="Rating">
<option value="0"></option>
<option value="1">Excellent</option>
<option value="2">Good</option>
<option value="3">Bad</option>
<option value="4">Awful</option>
</select>
<br/>
<textarea name ="Comments" rows="8" colspan="40">Comments:
</textarea>
<br/>
<input type="radio" name="Gender" id="male" value="male">Male
<input type="radio" name="Gender" id="female" value="female">Female
</fieldset>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
Javascript
function validateForm()
{ //Variable declarations for form inputs
var t = document.forms["review"]["Title"].value;
var e = document.forms["review"]["Email"].value;
var r = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var b = document.forms["review"]["Gender"].value;
var atsymb = e.indexOf("#");
var dotsymb = e.lastIndexOf(".");
if (t == null || t == "") {
document.getElementById("valAlert").innerHTML = "Title Missing";
return false;
}
else if (e == null || e == "" || atsymb < 1 || dotsymb < atsymb + 2 || dotsymb + 2 >= e.length)
{
document.getElementById("valAlert").innerHTML = "Email Missing";
return false;
}
else if (r == "0") {
document.getElementById("valAlert").innerHTML = "Please Rate the Movie, it's why you're here";
return false;
}
else if (c == null || c == "" || c.length < 10) {
document.getElementById("valAlert").innerHTML = "Reviews gotta be at least 10 characters!";
return false;
}
else if (b == null) {
document.getElementById("valAlert").innerHTML = "Please select Gender";
return false;
}
else {
alert("Review for " + t + " has been submitted, Good Job!");
return true;
}
}
You can use checked property to know if a option is checked.
document.getElementById('male').checked
The document is here:
http://www.w3schools.com/jsref/prop_radio_checked.asp
I guess what you would like to do is something like this:
var b = "";
if (document.getElementById('male').checked) {
b = document.getElementById('male').value;
}else if(document.getElementById('female').checked) {
b = document.getElementById('female').value;
}
if(b == "" | b == null ){
// alert
}
Hope this helps.
You have to check if b is undefined.
if (!b || b == null) {
I pared down the javascript and made a simple working demo:
http://jsfiddle.net/z7e7D/
Everything works fine when there is nothing in the email input, but as soon as I enter a "valid" email address, it doesn't even fire the function because the alert is never triggered. Any help will be appreciated.
Javascript (js/registration.js):
function validateForm() {
var value1 = document.forms["regForm"]["username"].value;
var value2 = document.forms["regForm"]["pass1"].value;
var value3 = document.forms["regForm"]["pass2"].value;
var value4 = document.forms["regForm"]["email"].value;
var atpos = value4.indexOf("#");
var dotpos = value4.lastIndexOf(".");
var check = true;
if(value1 == null || value1 == "") {
$("#userCheck").html("<img src='images/ico_fail.png'/> Please enter a user name! (25 character limit)");
check = false;
} else $("#userCheck").html("<img src='images/ico_pass.png'/>");
if(value2 == null || value2 == "") {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Please enter a password! (25 character limit)");
check = false;
} else {
if(value2.length < 8) {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Password must be 8 to 25 characters");
check = false;
} else $("#pass1Check").html("<img src='images/ico_pass.png'/>");
}
if(value3 == null || value3 == "") {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Please re-enter your password! (25 character limit)");
check = false;
} else {
if(value3 != value2) {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Password does not match!");
check = false;
} else $("#pass2Check").html("<img src='images/ico_pass.png'/>");
}
if(value4 == null || value4 == "") {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else {
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else $("#emailCheck").html("<img src='images/ico_pass.png'/>");
}
alert(check);
return check;
}
HTML:
<form name="regForm" method="post" action="" onsubmit="return validateForm();">
<input type="text" id="uName" name="username" size="25" maxlength="25" value=""/>
<span id="userCheck"> (25 character limit)</span></br>
<input type="password" id="password1" name="pass1" size="25" maxlength="25" value=""/>
<span id="pass1Check"> (25 character limit)</span></br>
<input type="password" id="password2" name="pass2" size="25" maxlength="25" value=""/>
<span id="pass2Check"></span></br>
<input type="text" name="email" size="25" value="" />
<span id="emailCheck"></span></br>
<input type="submit" name="submit" value="Register" />
<input type="hidden" name="perm" value="3" /> <!-- regular user -->
<input type="hidden" name="redirect" value="index.php" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
You dont have x defined here. i think it should be value4.length
The problem is: ReferenceError: x is not defined
At this line:
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
I am trying to get my validateForm() method to make sure email is valid (which I have done) and also make sure the 'name' and 'comments' fields are not empty. For some reason I cannot get the second part down, and need some assistance. Here is the current code I have.
<script type="text/javascript">
<!--
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var x = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
}
if (x == null || x == "") {
alert("Empty Fields");
return false;
}
}
// -->
</script>
And the form:
<form name="myForm" action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return validateForm()" method="POST">
Your name: <br>
<input type="text" name="name" ><br>
<br>
Your email: <br>
<input type="text" name="email"><br>
<br>
Your comments: <br>
<textarea name="comments" rows="15" cols="50"></textarea><br><br>
<input type="submit" value="Submit">
</form>
Why are you using same variable for both field name and email. It doesn't make sense.
There is one more syntax error in your code i.e. You have put an extra } before checking second condition. So it makes that condition outside of that function
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
}
So here is JS Fiddle Example
You are assigning both the form fields to the variable x
You should opt below points to keep in mind for above code
(1) validation for Empty fields should come first then Email checking.
(2) As per the code, your Empty field logic is not a part of validateForm() (It might be typo),so when validationForm() method will called,this logic won't execute
(3) you should write return true at the end of method validateForm()
(4) Use different variable names of field checking
GO through above points,it will be helpful to solve your Issue. :)
First there are syntax error in your code. It seems that there are two redunant curly braces. And then you assign both the two fields to x, and only the name field get its value. Also, you'd better first check the email field empty or not and then operate on it. Finally I don't think your check for email is right. For example: xxx#a.info. So you may try:
function checkEmail(aEmail){
var pattern=//w+([-+.']/w+)*#/w+([-.]/w+)*/./w+([-.]/w+)*/;
var objExp=new RegExp(pattern);
if(objExp.test(str)==true){
return true;
}else{
return false;
}
}
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].value;
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
if (!checkEmail(y)) {
alert("Not a valid email");
return false;
}
}
You should try this way:
function validateForm(){
var x=document.forms["myForm"].getElementsByName('email').value;
var y=document.forms["myForm"].getElementsByName('name').value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
alert("Not a valid e-mail address");
return false;
}
if (y==null || y==""){
alert("Empty Fields");
return false;
}
}