Verifying if the password field is empty - javascript

I have a login form in which the user enters the username and the password in an attempt to login to his profile. I want to dynamically verify that both the fields are filled before i start doing the server side processing.
<form id="form" method="post" action="student.jsp">
<label><strong>Username :</strong><br/><br/>
<input type="text" value="" name="username" id="idusername">
</label><br/><br/>
<label><strong>Password :</strong><br/><br/>
<input type="text" value="" name="password" id="idpassword">
</label><br/><br/><br/>
<input id="minibutton" name="send" type="submit" value="Login" />
</form>
I am using javascript which correctly verifies and alerts whenever the username is left blank and we attempt to login. However, it does not do so with the password field and we can get away with it being left blank.
$(document).ready(function(){
//global vars
var form = $("#form");
var username= $("#idusername");
var password = $("idpassword");
//On Submitting
form.submit(function(){
if(username.val().length==0 || password.val().length==0){
alert('Please enter the username');
return false;
}
else
{
if(password.val().length==0)
{
alert('Please enter the password');
return false;
}
else
return true;
}
});
});
I am not good at javascript but i need to use it for dynamic validation. Plaese pointy out the error in verifying the password field.

The missing hash symbol:
var password = $("idpassword");
should be:
var password = $("#idpassword");

change var password = $("idpassword"); to var password = $("#idpassword");

also in your logic:
if(username.val().length==0 || password.val().length==0){
alert('Please enter the username');
return false;
}
else{
if(password.val().length==0)
{
alert('Please enter the password');
return false;
}
else
return true;
}
if either the user name or password is empty, its always going to say "please enter the username" as it matches the if clause,
you should change it to 2 if's
if(username.val().length==0){
alert('Please enter the username');
return false;
}
if(password.val().length==0){
alert('Please enter the password');
return false;
}
return true;
That way, it checks if the user name is filled, then if the password is filled, if they both are, return true, else, if one is empty, it will flag it being empty and return false.
Hope this helps

Related

How do I check if input is blank/not blank and do specific thing

Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.

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 make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

form validation error

I have little problem with form and I am using js for validation.
Here is my form code.
<form method="get" onkeydown="checkEnter()" action="emailform.php" id="signupform" name="subscribe">
<input name="email" id="email" type="text" value="Enter Email for Updates" onfocus="if(this.value=='Enter Email for Updates'){this.value=''};" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
id signupform I am using for validation and submit the form is on pressing enter button.
But there is problem when put signupform then my validation start working fine and when I enter correct email it's show me error and when I remove the signupform id then my form submission work fine without validation.
Here is my JS code for id signupform.
function SubscribeForm() {
$('#signupform').submit(function () {
$('.email').removeClass('error')
$('em.error').remove();
var error = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($.trim($('.email').val()) == '') {
$(this).append('<em class="error">Please enter your email address.</em>');
$(this).addClass('error');
error = true;
} else if (!emailReg.test(jQuery.trim($('.email').val()))) {
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
error = true;
}
if (!error) {
$("#submit", this).after('<span id="form_loading"></span>');
var formValues = $(this).serialize();
$.post($(this).attr('action'), formValues, function (data) {
$("#signupform").before(data);
});
$(':input[type="text"]').attr('value', '');
}
return false
});
}
change
return false
to
return error;
it is causing problem.
change
return false;
to
return !error;
Also, add css class "email" to input email field, or change jquery to selector code ".email" to "#email"
Also a possible solution, if you don't need to support the old browser: placeholder.
<input placeholder="Enter email" type="text"... />
Thanks for your help Guys. i just put this and now working fine.
$('#signupform').submit(function(){
$('.email').removeClass('error')
$('em.error').remove();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
sEmail = document.getElementById('email').value;
if (filter.test(sEmail)) {
return true;
}
else {
if(sEmail == '')
{
$(this).append('<em class="error">Please enter your email address</em>');
$(this).addClass('error');
}
else
{
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
}
return false;
}
});
});

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources