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;
}
Related
I am trying to validate each field and display appropriate error messages using defined formatting. The username displayed appropriate error message, but the rest of the code is not "working". The email field was working, but after I store the variables atEmail and dotEmail, it didn't work anymore. I have been trying at this for a couple of days already. Any suggestions is greatly appreciated.
function validateForm() {
var firstPassword = document.myForm.passwordOne.value;
var secondPassword = document.myForm.passwordTwo.value;
var emailID = document.myForm.email.value;
var alphaNumeric = /^[\w ]+$/;
var letters = /^[A-Za-z]+$/;
var atEmail = emailID.indexOf("#");
var dotEmail = emailID.lastIndexOf(".");
var phone = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!alphaNumeric.test(document.myForm.userName.value)) {
alert( "Please enter letters and numbers only!" );
document.myForm.userName.focus() ;
return false;
}
if(firstPassword.value.length < 8) {
alert( "Password must be at least 8 characters" );
document.myForm.passwordOne.focus() ;
return false;
}
if(document.myForm.firstPassword.value != document.myForm.secondPassword.value ) {
alert( "Password must match!" );
document.myForm.passwordTwo.focus() ;
return false;
}
if(!letters.match(document.myForm.firstName.value)) {
alert( "Your first name should only contain letters!" );
document.myForm.firstName.focus() ;
return false;
}
if(!letters.match(document.myForm.lastName.value)) {
alert( "Your last name should only contain letters!" );
document.myForm.lastName.focus() ;
return false;
}
if (atEmail < 1 || ( dotEmail - atEmail < 2 )) {
alert("Please enter valid email address format: xxx#xxx.xxx");
document.myForm.email.focus() ;
return false;
}
if(phonenumber.value.match(phone)) {
alert( "Please enter valid phone number format:(xxx) xxx-xxxx" );
document.myForm.phonenumber.focus() ;
return false;
}
if((document.myForm.signUpNewletter[0].checked == false) &&(document.myForm.signUpNewletter[1].checked == false )) {
alert( "Please check yes or no!" );
document.myForm.signUpNewsletter.focus() ;
return false;
}
return true;
}
Are you sure this is correct?
if(document.myForm.firstPassword.value != document.myForm.secondPassword.value ) {
You have already defined firstPassword and secondPassword variables, then why use them in document.myForm.firstPassword and document.myForm.secondPassword
Working on a web page which used to have a working email validation, but after adding in a few additional features it suddenly no longer works. The page shouldn't proceed unless all fields are valid, everything is basically client-side if you're wondering why it's a bit of a weird website.
Originally the e-mail validation worked for if the field was blank or did not have an '#' and '.' following it, using the code:
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
However, added with the entire code of:
function validateForm(){
{
var f=document.forms["registration"]["FirstName"].value;
var a=document.forms["registration"]["Surname"].value;
var b=document.forms["registration"]["address"].value;
var c=document.forms["registration"]["post"].value;
var d=document.forms["registration"]["email"].value;
var z=document.forms["registration"]["password"].value;
if (f==null || f=="")
{
document.forms["registration"]["FirstName"].focus();
alert("Please enter your first name");
return false;
}
if (a==null || a=="")
{
document.forms["registration"]["Surname"].focus();
alert("Please enter your surname");
return false;
}
if (b==null || b=="")
{
alert("Please enter your address");
document.forms["registration"]["address"].focus();
return false;
}
if (c==null || c=="")
{
alert("Please enter your postcode");
document.forms["registration"]["post"].focus();
return false;
}
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
}
}
It no longer works...? Puzzled, any help appreciated.
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!!
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;
}
Hi i am wondering if there is any way of stopping my forms from clearing after I submit and the validation error comes up?
Just to clarify I have multiple forms, when user submits I am using js to validate, when the validation error alerts all the forms reset is there any way to stop that??? "yes it does have to be javascript"
<script>
//calender dropdown menu
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield,init){
var dayfield=document.getElementById(dayfield);
var monthfield=document.getElementById(monthfield);
var yearfield=document.getElementById(yearfield);
var today=(init)?new Date():new Date(yearfield.value*1,monthfield.value*1)
dayfield.options.length=0;
for (var i=0; i<new Date(today.getFullYear(),today.getMonth()+1,-1).getDate(); i++) dayfield.options[i]=new Option(i+1,i+1)
dayfield.selectedIndex=(init)?today.getDate()-1:0; //select today's day
if (init){
for (var m=0; m<12; m++) monthfield.options[m]=new Option(monthtext[m],m);
}
monthfield.selectedIndex=(init)?today.getMonth():0; //select today's day
if (init){
var thisyear=today.getFullYear()
for (var y=0; y<20; y++) yearfield.options[y]=new Option(thisyear, thisyear++)
}
}
// function validate
function validate_form ()
{
valid = true;
// validate name
if ( document.input.name.value == "" )
{
alert ( "Please enter your name" );
valid = false;
}
// validate address
if ( document.input.address.value == "" )
{
alert ( "Please enter your address address" );
valid = false;
}
// validate suburb town
if ( document.input.town.value == "" )
{
alert ( "Please enter your Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById('postcode').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById('postcode').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById('postcode').focus();
return false;
}
// validate home phone
var y = document.getElementById('hphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x=document.forms["input"]["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;
}
}
{
// validate radio buttons
var o = document.getElementById('1');
var t = document.getElementById('2');
if ( (o.checked == false ) && (t.checked == true ) )
{
// validate alternative address
if ( document.input.street.value == "" )
{
alert ( "Please enter alternative address address" );
valid = false;
}
// validate suburb town
if ( document.input.suburb.value == "" )
{
alert ( "Please enter alternative Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById('postcode2').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
// validate message box
var o = document.getElementById('card');
if ( (o.checked == true ))
{
if ( document.input.message.value == "" )
{
alert ( "Please enter message" );
valid = false;
}
return valid;
}
}
}
}
</script>
<input type="submit" value="Submit" />
ID values should not begin with numbers.
Here is a short example of capturing and affecting the outcome of a form submission.
One of the most common mistakes is forgetting to return the value of the onsubmit function.
Without a complete example, preferrably a fiddle, it isn't easy to know precisely what's wrong.