I'm trying to validate my form, and the first alert works. But then when the user fills in correct data and clicks submit, the form does not submit anymore. Any help is appreciated, thanks!
<form name="register" action="register.php" onsubmit="return validateForm()" method="post">
// form stuff
function validateForm() {
if (!checkName() || !checkEmail()) {
return false;
} else {
return true;
}
}
function checkName() {
var name=document.forms["register"]["name"].value;
if (name==null || name=="") {
alert("Please fill out your name");
return false;
}
}
function checkEmail() {
var email=document.forms["register"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
}
You need checkEmail and checkName to return true when the email or name is present. What you've got now returns undefined.
Here is a fiddle showing the solution and here are the two functions rewritten:
function checkName() {
var name = document.forms["register"]["name"].value;
if (name == null || name == "") {
alert("Please fill out your name");
return false;
}
return true;
}
function checkEmail() {
var email = document.forms["register"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
I do ultimately think you'll be happier if you wind up going to jQuery Validation, though.
Related
Problem: External javascript is not working.
I want my registration page to be validated and I have written the code but I don't know where to call it I tried the following.
This is my javascript code:
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]*\.[A-Za-z]{2,5}$/;
var fname = document.form.Name.Value;
var lname = document.form.Last.value;
var fpassword = document.form.password.value;
var frassword = document.form.repassword.value;
var femail = document.form.Email.value;
function submit()
{
if ( fname === "")
{
document.form.Name.focus();
alert("Please enter the name");
return false;
}
if ( lname === "")
{
document.form.Last.focus();
alert("Please enter last name");
return false;
}
if( fpassword === "")
{
document.form.password.focus();
alert("You can't leave password empty");
return false;
}
if( frassword === "")
{
document.form.repassword.focus();
alert("Please confirm password");
return false;
}
if( femail === "")
{
document.form.Email.focus();
alert("Don't leave Email blank");
return false;
}
else if (!emailRegex.test(femail))
{
document.form.Email.focus();
alert("Not a valid Email");
return false;
}
if( fname !== '' && lname !== '' && fpassword !== '' && frassword !== '' && femail !== '')
{
alert("Registration sucessfull");
}
}
I tried like this :
<script type="text/javascript" src="skill.js"></script>
<script>
submit();
</script>
And I tried this too:
<form name="form" onclick="submit()">
create a submit button inside the form element like this -
<input type="submit" value="Submit" />
and then add an attribute on the opening form tag, like this-
<form name="form" onsubmit="submit()">
make sure you have linked to you JS file already.
I am having a problem validating a form. When it submits it just runs the last function. When i try to combine them with a comma then it just runs them all consecutively. Here is my code:
<script type= "text/javascript">
function validateForm() {
var x = document.forms["myForm"]["name"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
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;
}
}
function validateForm() {
var x = document.forms["myForm"]["message"].value;
if (x == null || x == "") {
alert("Please Send Us a Message");
return false;
}
}
</script>
JavaScript doesn't handle redeclaring functions with the same name.
What is wrong with:
function validateForm() {
// x is a bad name for the variable.
var x = document.forms["myForm"]["name"].value;
// x can never be null, BTW.
if (x === "") {
alert("Name must be filled out");
return false;
}
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;
}
x = document.forms["myForm"]["message"].value;
if (x === "") {
alert("Please Send Us a Message");
return false;
}
}
Don't name your functions with the same name! You can call them validateName, validateEmail and validateMessage.
When you declare functions with the same name, the previous functions will be overriden by the last one.
If you want to call one function in onsubmit, you can set onsubmit=validteForm() and declare validateForm as:
function validateForm() {
validateName();
validateEmail();
validateMessage();
}
You are trying to have more than one value in one variable, which is not possible. The value you are defining will overwrite the definition which is already there. Change your function names.
Do it like bellow
<script>
function fun1 () {
alert('in first')
}
function fun2 () {
alert('in Second')
}
function fun3 () {
alert('in third')
}
</script>
call them like bellow onsubmit of form
<form action="" onsubmit="fun1();fun2();fun3();">
<input type="submit" value="click">
</form>
Another solution; you can modify your function(s) to a simple one, like following
function validateForm(){
var x, atpos, dotpos;
x = document.forms["myForm"]["name"].value;
if(!x){
alert("Name must be filled out");
return false;
}
x = document.forms["myForm"]["email"].value;
atpos = x.indexOf("#");
dotpos = x.lastIndexOf(".");
if(atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length){
alert("Not a valid e-mail address");
return false;
}
x = document.forms["myForm"]["message"].value;
if(!x){
alert("Please Send Us a Message");
return false;
}
return true;
}
I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}
My goal is this:
Check if email and name are empty. If so, give 'Enter email or name' alert.
If they do, check for an # in email If none is found, give 'Bad email' alert.
Check if email and name contain any letters, if they do, give 'Success' alert
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");}
return false;
if(email.indexOf("#") == -1){
alert("Bad email");}
return false;
var a = email.length;
var b = name.length;
if(a==>0, b==>0){
alert("Message sent");}
return true;
}
This is what I've come up with so far, but it isn't working. I'm quite new at javascript so maybe you guys could tell me what I've done wrong?
The problem you're having is the close bracket is in the wrong place. You have it at the end of your alert statement and you probably want the return to be included with your if statement. if this is the case then change it to be:
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");
return false;
}
if(email.indexOf("#") == -1){
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if(a > 0 && b > 0){
alert("Message sent");
return true;
}
}
A better way to do the same thing would be because that way you're not checking the variables for length and size twice:
function test(email, name) {
var a = email.length;
var b = name.length;
if ( a > 0 && b > 0 ) {
// ignore 0 because email addresses shouldn't start with #
if ( email.indexOf("#") > 0 ) {
alert("Message sent");
return true;
}
else {
alert("Bad email");
return false;
}
}
else {
alert("Enter mail or name");
return false;
}
}
Try this JSFiddle that seems to fit your needs http://jsfiddle.net/9nF5W/
function test(email, name) {
if (email == "" || name == "") {
alert("Enter mail or name");
return false;
}
if (email.indexOf("#") == -1) {
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if (a > 0 && b > 0) {
alert("Message sent");
}
return true;
}
test('tes#t', 'test');
I think there is an other mistake than the returns statements in "if(a==>0, b==>0){" by the way.
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;
}
}