HTML/JavaScript Validation Issues - javascript

Part of a website I'm building I'm trying to validate the registration from. The code works it's just once it gets to validating the firstname it seems to quit and return true.. I'm lost on how to fix it as I haven't encountered this issue before and I cannot see anything wrong with my code..
function validateForm(){
var x = document.registration.email.value;
var atPos = x.indexOf("#");
var dotPos = x.lastIndexOf(".");
if(document.registration.user.value.length < 4){
window.alert("Please enter a valid username. (4 - 20 Characters)");
document.registration.user.focus();
return false;
}
if(document.registration.pass.value.length < 4){
window.alert("Please provide a valid password. (4 - 50 Characters)");
document.registration.pass.focus();
return false;
}
if(atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= x.length) {
window.alert("Invalid email format.");
document.registration.email.focus();
return false;
}
if(document.registration.firstname.value.length < 3){
window.alert("Please provide a valid firstname. (3 - 20 Characters)");
document.registration.fistname.focus();
return false;
}
if(document.registration.surname.value.length < 3){
window.alert("Please a valid surname. (3 - 20 Characters)");
document.registration.surname.focus();
return false;
}
if(document.registration.country.value.length < 3){
window.alert("Please provide valid Country. (3 - 20 Characters)");
document.registration.country.focus();
return false;
}else{
return true;
}
}
<form name="registration" action="registration.php" method="post" onsubmit="return validateForm()">

You have a typo for the firstname field:
document.registration.fistname.focus();
You can check your browser's element inspector for any javascript errors after submitting the form.

its returning true only if your conditional for country is met. try using if else if and else
function validateForm(e){
e.preventDefault();
var x = document.registration.email.value;
var atPos = x.indexOf("#");
var dotPos = x.lastIndexOf(".");
if(document.registration.user.value.length < 4){
window.alert("Please enter a valid username. (4 - 20 Characters)");
document.registration.user.focus();
return false;
}
else if(document.registration.pass.value.length < 4){
window.alert("Please provide a valid password. (4 - 50 Characters)");
document.registration.pass.focus();
return false;
}
else if(atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= x.length) {
window.alert("Invalid email format.");
document.registration.email.focus();
return false;
}
else if(document.registration.firstname.value.length < 3){
window.alert("Please provide a valid firstname. (3 - 20 Characters)");
document.registration.fistname.focus();
return false;
}
else if(document.registration.surname.value.length < 3){
window.alert("Please a valid surname. (3 - 20 Characters)");
document.registration.surname.focus();
return false;
}
else if(document.registration.country.value.length < 3){
window.alert("Please provide valid Country. (3 - 20 Characters)");
document.registration.country.focus();
return false;
}else{
return true;
}
}

Related

JavaScript/ Alphanumeric validation not working

I have this reg ex for alphanumeric validation that I got from this post
but it is not working with this function (I have a similar function for email and it works)
function checkName(field) {
var x = document.getElementById(field).value;
var y = /^[a-z0-9]+$/i;
//var z = /^[0-9]*$/;
if (x == "" || !x.match(y) ) {
alert("Invalid character");
if (x.length <= 2 || x.length >= 15) {
alert("Insert a name between 3 and 15 characters");
}
return false;
}
}
If I write some string/name I get both alerts. Can someone tell me what is wrong with this function?
Below is the approach for alphanumeric validation:
function checkName(field)
{
var x = document.getElementById(field).value;
if (x.length <= 2 || x.length >= 15)
{
alert("Insert a name between 3 and 15 characters");
return false;
}
var y = /^[0-9a-zA-Z]+$/;
if (x == "" || !x.match(y) )
{
alert("Invalid character");
return false;
}
alert("ALL OK");
return true;
}
<input type="text" id="textName" />
<button onClick="checkName('textName');">Check</button>
The Regex check for capital and small alphabets and numbers, and also checks for the length.
Your code works for me
function checkName(field) {
console.log(field);
var x = field;
var y = /^[a-z0-9]+$/i;
if (x == "" || !x.match(y) ) {
console.log("Invalid character");
}
if (x.length <= 2 || x.length >= 15) {
console.log("Insert a name between 3 and 15 characters");
}
}
//valid
checkName('testdskfjskdlf');
//invalid
checkName('slkjf*%');
//too long
checkName('jjjjjjjjjjjjjjjjjjjjjjjjjjj');

why is my javascript not working on my php page?

I am facing issue with javascript for form validation.
On one of the forms the javascript function is working properly, and when on other form, i am trying to do form validation, but the script does not fire up.. i have tried many times to clear my browser cache and refreshed the page but i am not getting any results.
I would be thankful if anyone reviews it and help spot the issue.
The following is the function that works on my homepage:
<script>
function validate()
{
var uid = document.getElementById("usrname").value;
var pwd = document.getElementById("passwd").value;
if (uid == "" || pwd == "") {
alert("Empty fields not allowed");
return false;
}
else if (uid.length < 4 || uid.length > 20) {
alert("User ID string length should be between 4 - 20");
return false;
}
else if (pwd.length < 6 || pwd.length >20) {
alert("Password length should be between 6 - 20");
return false;
}
return true;
}
</script>
<form name="ulogin" action="login.php" method="post" onSubmit="return validate();">
The following validation code on the other page does not run:
<script>
function regval()
{
var cname = document.getElementById("name1").value;
var email = document.getElementById("email").value;
var phn = document.getElementById("phone").value;
var addr1 = document.getElementById("addr1").value;
var addr2 = document.getElementById("addr2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var uname = document.getElementById("uname").value;
var pwd = document.getElementById("passwd").value;
var cnfp = document.getElementById("cnf_passwd").value;
var secans = document.getElementById("sec_ans").value;
var regex=/^[0-9]+$/;
var alphanum=/^[a-z0-9]+$/i;
if(cname == "" || email == "" || phn == "" || addr1 == "" || addr2 == "" || city == "" || state == "" || state == "" || country == "" || uname == "" || pwd == "" || cnfp == ""|| secans == "") {
alert("Empty fields not allowed");
return false;
}
if (cname.length < 3 || cname.length > 20) {
alert("Name length should be between 4-20 characters.");
return false;
}
if (email.length < 10 || email.length > 50 ) {
alert("email length should be between 10-50 characters.");
return false;
}
if (phn.length < 7 || phn.length > 11 ) {
alert("check phone number length.");
return false;
}
else if (!phn.match(regex)) {
alert("Please check inputs, only numbers are allowed.!");
return false;
}
if (city.toLowerCase() != "surat" || state.toLowerCase() != "gujarat" || country.toLowerCase() != "india") {
alert("Sorry, we only serve in surat currently at the moment..!!");
return false;
}
if (uname.length < 4 || uname.length > 20) {
alert("user name should be between 4 - 20 characters.");
return false;
}
else if (!uname.match(alphanum)) {
alert("only characters A-z 0-9 are allowed.");
return false
}
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
if (pwd != cnfp) {
alert("the passwords do not match, please check and try again.");
return false;
}
if (secans.length < 5 || secans.length > 20) {
alert("please check for security answer length. It should be between 5 to 20 characters.");
return false;
}
return true;
}
</script>
<form name="usreg" action="signup.php" method="POST" onSubmit="return regval();">
the script tags are in the head tags of my webpage.
Thanks in advance.
Missing closing bracket ) Here else if (!pwd.match(alphanum) {
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Should be
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum)) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Note: Always check browser console log for errors.

I am trying to validate a form with more than one function, but it only calls the last one even if i combine them with a comma

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;
}

How do I correctly perform form validation in JavaScript?

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;
}

JS Form Validation - Submit Button does nothing

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.

Categories