Check my javascript codes - javascript

Can someone check my javascript codes, if they are correct ? I am not able to see email alert. I tried to click submit button but after name alert, email isn't working.
function doValidate()
{
if (document.appointment.requiredname.value =="")
{
alert("Please put your name");
document.appointment.requiredname.focus();
return false;
}
var readmail = document.appointment.requiredemail.value;
var checkatsymbol = readmail.indexof("#");
var checkdotsymbol = readmail.lastindexof(".");
if (checkatsymbol < 1 || checkdotsymbol+2>=readmail.length )
{
alert("Please put the correct email address");
document.appointment.requiredemail.focus();
return false;
}
if (document.appointment.requiredphone.value =="" )
{
alert("Please put your phone");
document.appointment.requiredphone.focus();
return false;
}
if (document.appointment.requireddate.value =="" )
{
alert("Please put your appointment date as DD/MM/YYYY");
document.appointment.requireddate.focus();
return false;
}
if (document.appointment.requiredtime.value =="")
{
alert("Please put your appointment time as HH:MM AM/PM");
document.appointment.requiredtime.focus();
return false;
}
return ( true );
}

you have to remove return false; from your if conditions in order to execute the folowing codes in a function

wirte 'indexOf' not 'indexof' replace:
var checkatsymbol = readmail.indexof("#");
var checkdotsymbol = readmail.lastindexof(".");
with :
var checkatsymbol = readmail.indexOf("#");
var checkdotsymbol = readmail.lastindexOf(".");

Javascript is case-sensitive.
var checkatsymbol = readmail.indexof("#");
var checkdotsymbol = readmail.lastindexof(".");
should be:
var checkatsymbol = readmail.indexOf("#");
var checkdotsymbol = readmail.lastIndexOf(".");

You should probably head for CodeReview, a StackExchange Forum

var x=document.appointment.requiredemail.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;
}
This snippet to validate email should work!!

Related

How to I validate a password using regular expressions in javascript?

This is my code. It functions perfectly up to the password validation. It completely ignores my null test and goes straight to the actual validation but then refuses to go past it and keeps giving me my invalid password alert. Any ideas as to how to fix this issue?
function validate(){
var l = document.getElementById('lname').value;
var f = document.getElementById('fname').value;
var e = document.getElementById('email').value;
var e2 = document.getElementById('cemail').value;
var u = document.getElementById('newuser').value;
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
var str = new RegExp(/[a-zA-Z]{1,30}$/);
var em = new RegExp(/[a-z0-9._-]+#[a-z]+\.[a-z]{1,30}$/);
var pass = new RegExp(/[a-zA-Z0-9]{1,15}$/);
if (l == null || l == ""){
alert("Please enter your last name");
return false;
}
var ln = str.test(l);
if(ln==false){
alert("Invalid Name.");
documents.forms['registration']['lname'].focus;
return false;
}
if (f == null || f == ""){
alert("Please enter your first name");
return false;
}
var fn = str.test(f);
if(fn==false){
alert("Invalid Name.");
documents.forms['registration']['fname'].focus;
return false;
}
if (e == null || e == "") {
alert("Please enter an email address");
return false;
}
if (e2 == null || e2 == "") {
alert("Please enter an email address");
return false;
}
var eml = em.test(e);
if(eml==false){
alert("Invalid Email.");
documents.forms['registration']['email'].focus;
return false;
}
var eml2 = em.test(e2);
if(eml2==false){
alert("Invalid Email.");
documents.forms['registration']['cemail'].focus;
return false;
}
if(e2!=e){
alert("Please ensure that the emails match.");
return false;
}
if (u == null || u == "") {
alert("Please enter a user name");
return false;
}
var un = str.test(u);
if(un==false){
alert("Invalid user name");
documents.forms['registration']['newuser'].focus;
return false;
}
if (p == null || p == "") {
alert("works");
alert("Please enter a password");
return false;
}
if (p2 == null || p2 == "") {
alert("Please enter a password");
return false;
}
var pwrd = pass.test(p);
if(pwrd==false){
alert("Invalid Password.");
documents.forms['registration']['newpass'].focus;
return false;
}
if(p2!=p){
alert("Please ensure that the passwords match");
documents.forms['registration']['cnewpass'].focus;
return false;
}
}
You should amend js code that retriving data from from. Look,
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
Here You are trying to get NOT values of input tags, you are trying to get tag.
So You should replace above code with:
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;
I hope it will help you
You should pass the value of password fields.
try changing the code to
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

nested if else in javascript

I have trouble with the nested if structure in javascript. Any help is appreciated.
function validateForm()
{
var a = document.forms["demo1"]["addr1"].value;
var b = document.forms["demo1"]["city"].value;
//var c = document.forms["demo1"]["fname"].value;
//var d = document.forms["demo1"]["lname"].value;
//var f = document.forms["demo1"]["phno"].value;
//var g = document.forms["demo1"]["email"].value;
//var g1 = document.forms["demo1"]["cemail"].value;
//var h = document.forms["demo1"]["pwd"].value;
//var h1 = document.forms["demo1"]["cpwd"].value;
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
break;
}
else if(a=="" || a==null)
{
alert("Please enter your address");
return false;
break;
}
else {return true;}
}
<form name = "demo1" action = "exp2.php" onsubmit = "return validateForm()" method = "POST">
The code works fine(as intended) if there is only one if statement. But I am not getting the intended result if more than one if else is been deployed.
Regards,
Mani
First, you don't need break statements, they're useless in this context.
Second, you don't need to nest and, in fact, you shouldn't since checking of a and b is independent of each other:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
return true;
What about shorten ur code with reusable isEmpty function
function validateForm()
{
var isEmpty = function ( name , label ){
var val = document.forms["demo1"][ name ].value;
if( ! val )
{
alert("Please enter your "+ label );
return true;
}
return false;
}
return !isEmpty( 'city', 'city') &&
!isEmpty( 'addr1', 'address');
}
isEmpty return true or false
if(b=="" || b==null) {
alert("Please enter your city");
return false;
}
else if(a=="" || a==null) {
alert("Please enter your address");
return false;
}
else {
return true;
}
Like paxdiablo says you can use two separate if statements.
But if you only want to require an address when a city is entered you must realize that this is not a nested if statement. This is:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
else
{
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
else
{
return true;
}
}
A more reabable version would be, imo:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if((b=="" || b == null) && (a=="" || a==null))
{
alert("Please enter your address");
return false;
}

Calling a regular expression in a javascript function

I've spent many hours trying to work this out. I know it's something easy but it just will not work for me!
I would like to validate for a password using this expression ^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$ with javascript.
I'm not sure how to structure the function and how to call it in the code. I've got something working for validating the email but I can't make the password expression work.
function validateEmail()
{
var emailID = document.myForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email address")
document.myForm.email.focus() ;
return false;
}
return( true );
}
function validate()
{
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}
else
{
// Put extra check for data format
var ret = validateEmail();
if( ret == false )
{
return false;
}
}
I would like to call the passwordChecker from the validate function.
This should do
function validateEmail()
{
var emailID = document.myForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email address")
document.myForm.email.focus() ;
return false;
}
return true;
}
function validatePassword()
{
var reg = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
return reg.test(document.myForm.password.value);
}
function validate()
{
if(document.myForm.email.value == "" || !validateEmail())
{
alert( "Please provide a valid Email!" );
document.myForm.email.focus() ;
return false;
}
else if(!validatePassword())
{
alert("Please provide a valid password!");
document.myForm.password.focus() ;
return false;
}
return true;
}
My suggestion
function isEmail(email) {
var re = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
return re.test(email);
}
function validate() {
var email = document.myForm.email;
if (email.value.trim() =="") { // may need IE support
alert( "Please provide your Email!" );
email.focus() ;
return false;
}
if (!isEmail(email.value)) {
alert( "Please provide a valid Email!" );
email.focus() ;
return false;
}
return true;
}

HTML form validation using JS

I'm creating form validation, but can't figure out how to use checking preg_match from variable. Checking just for empty fields working fine, but its not enough. Any advice?
var tekst = /([a-zA-Z0-9]|[a-zA-Z0-9])/;
var myForm = document.forms.formaa;
var prek = myForm.elements['preke'];
var kaina = myForm.elements['kaina'];
var k = myForm.elements['kiekis'];
var uzsak = myForm.elements['uzsakymas'];
if (uzsak.value == ''){
alert("neuzpildyta");
return false;
}
for (var i = 0; i < prek.length; i++) {
var preke = prek[i];
var kai = kaina[i];
var kie = k[i];
if (preke.value == '' || (preke.value).test(tekst) == false){
alert("neuzpildyta");
return false;
}
if (kai.value == ''){
alert("neuzpildyta");
return false;
}
if (kie.value == ''){
alert("neuzpildyta");
return false;
}
}
You can also use like this,
if (x==null || x=="") {
document.getElementById('name').innerHTML="Name must be filled out";
return false; }
For More This one help's you JavaScript Validation.
Rather than rolling your own validation, have you considered using something like jQuery validation?

Categories

Resources