Javascript validation for email making issues - javascript

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.

As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now

Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.

You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.

Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Related

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

How to Validate Email or Phone Number Using Single Input like Facebook

How to validate Email or Phone Number Using Single Input?
I like to have input value xyz#gmail.com OR 1234567890 anything else alert "Invalid Email or phone number"
Like Facebook Sign Up form
<form>
<input type="text" placeholder="Email or mobile number" />
<button type="submit" >Sign Up</button>
</form>
Thanks!!
I Did using two regular expressions like
function validateEmail() {
var email = document.getElementById('txtEmail');
var mailFormat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([0-9]{10})+$/;
if (email.value == "") {
alert( " Please enter your Email or Phone Number ");
}
else if (!mailFormat.test(email.value)) {
alert( " Email Address / Phone number is not valid, Please provide a valid Email or phone number ");
return false;
}
else {
alert(" Success ");
}
}
I'd probably test it with two regexes. First check for one (e.g. is it a valid email), then if that fails, check it with the other (e.g. is it a valid phone number). If neither, show a validation message saying that the value is invalid. I won't supply regex examples here as there are dozens of those around the internet and each has pros and cons - no sense starting a flame war over the best regex for email or phone, but the code would look like the following:
function validateEmailPhoneInput(field)
{
if (emailRegex.test(field.value))
{
//it's an email address
}
else if (phoneRegex.test(field.value))
{
//it's a phone number
}
else
{
//display your message or highlight your field or whatever.
field.classList.add('invalid');
}
}
Try this it's working:
<script>
$(document).ready(function () {
$("#cuntryCode").hide();
$("#useridInput").on('input', function () {
var len = $("#useridInput").val().length;
if (len >= 2) {
var VAL = this.value;
var intRegex = /^[1-9][0-9]*([.][0-9]{2}|)$/;
if (!intRegex.test(VAL)) {
$('#error-caption').html('Invalid email. Please check spelling.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").hide();
} else {
if(len < 10){
$('#error-caption').html('Invalid mobile number. Please try again.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").show();
}else{
$('#error-caption').html('Invalid mobile number. length must be 10 digit.');
$('#error-caption').css('color', 'red');
}
}
}else{
$("#cuntryCode").hide();
$('#error-caption').html('');
}
});
});
</script>
<form class="push--top-small forward" method="POST" data-reactid="15">
<h4 id="input-title" data-reactid="16">Welcome back
</h4>
<label class="label" id="input-label" for="useridInput" data-reactid="17">Sign in with your email address or mobile number.
</label>
<div style="margin-bottom:24px;" data-reactid="18">
<div >
<div id="cuntryCode" class="_style_4kEO6r" style="float: left; height: 44px; line-height: 44px;">
<div tabindex="0" > +241
</div>
</div>
<div style="display:flex;">
<input id="useridInput" autocorrect="off" autocapitalize="off" name="textInputValue" class="text-input" placeholder="Email or mobile number" aria-required="true" aria-invalid="false" aria-describedby="error-caption input-title">
</div>
</div>
<div id="error-caption">
</div>
</div>
<button class="btn btn--arrow btn--full" data-reactid="24">
<span class="push-small--right" data-reactid="25">Next
</span>
</button>
</form>
$("#volunteer_submit").click(function myfunction() {
function email_number_check() {
var email_number = $("input[name=email_mobile]").val();
if (email_number == "") {
alert("Fill in the Required Fields field cannot be empty");
}
else if (isNaN(email_number) == true) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email_number) == false) {
alert('Invalid Email Address');
}
else {
$("#contact-form").submit();
}
}
else if (isNaN(email_number) == false) {
var reg_mobile = /^(\+\d{1,3}[- ]?)?\d{10}$/;
if (reg_mobile.test(email_number) == false) {
alert('Invalid mobile');
}
else {
$("#contact-form").submit();
}
}
}
email_number_check();
});
This code is worked for me.
var a=document.getElementById('txtEmail').value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(a=="")
{
alert('Please enter value');
return false;
}
else if(isNaN(a))
{
if(!(a.match(mailformat)))
{
alert('Please enter email address/phno valid');
return false;
}
}
else
{
if(a.length()!=10)
{
alert('Please enter valid phno');
return false;
}
}

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

How to get `form.field.value` in jQuery?

in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin:
https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this represents the form element so you could just do this.uName.value and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val() is jquery method, and in plain javascript you would use value and in this case that should be sufficient enough.
This will help you:
jQuery(function($) {
var $username = $('#uName'),
$password = $('#passKey');
$('form').submit(function() {
if ($username.val() == '') {
alert('Please enter username');
$username.focus();
} else if($password.val() == '') {
alert('Please enter username');
$password.focus();
} else {
return true;
}
return false;
});
});
Some points you need to keep in mind:
If you will work with the DOM you should wrap your code inside a jQuery(function() { ... }); block.
If you want to access a DOM element with jQuery you need to select it before using $(...).

Categories

Resources