condtion in javascript validation not working properly - javascript

I have a textbox and a submit button
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
Here is the function code:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
now what is want is that if the user leaves the filed empty it should only highlight the textbox with backgound color red and if the username is less than 8 characters it should show the message and highlight the backgound of textbox but now even if the textbox is empty it is displaying the message which i dont want...if the field is empty it should ol

I think your second conditional is wrong. Also you can write the code much cleaner like this:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}

Related

Regex for 2 Upper case Alphabet followed by 3 numbers

I'm new to regex and facing issue in below problem statement.
Problem statement : What I need is a text box where the content must start with 2 upper case alphabets and follows by 3 digits. This textbox can be empty.
function validateModuleCode()
{
var m = document.getElementById("moduleCode").value;
if (/^[A-Z]{2}[0-9]{3}$/.test(m) == false)
{
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
}
else
{
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
Module Code:
<br/>
<input type = "text" id = "moduleCode" name = "module code" onkeypress = "validateModuleCode()">
<span style = "color:red" id = "moduleError"></span>
<br/><br/>
However, the moduleError keeps popping out and shows invalid even though I have entered a valid value. Here is the error image.
How do I correct this ?
You can use oninput event to get the updated input value. Also, You have to add a check for the empty value. So that it should be valid if there is no value in the text box.
Live Demo :
function validateModuleCode() {
var m = document.getElementById("moduleCode").value;
if (m && (/^[A-Z]{2}[0-9]{3}$/.test(m) === false)) {
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
} else {
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
<input type="text" id="moduleCode" name="module code" oninput="validateModuleCode()">
<span style="color:red" id="moduleError"></span>

Why is nothing happening when I click on onclick button?

*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.

How can this Javascript code handle the if/else statements better, or possibly use switches?

First off, if this is against the rules, or frowned upon I'm very sorry and feel free to downvote/close. I'm desperately stuck.
I'm having trouble with an HTML page I wrote which is supposed to consist of inputs with certain requirements, adding div's to display error messages , and automatically update those error messages onblur. The assignment was made to test our javascript skills, and thus must be completely validated through javascript.
Here are a few of the guidelines...
validating the form for four separate things:
presence of required fields
equality of password fields
conformance to a password policy (one uppercase, one number, length > 7)
validity of the email address
When any one of these are violated, I should deactivate the form’s submit button so that it is not clickable and add a child "div" to the error-display containing an error message describing the situation.
The code seems correct to me, and works spontaneously, but i believe since javascript is looked at one line at a time it isn't displaying error messages correctly or even getting to certain parts of my code at all.
Here is my large chunk of javascript code, I am mainly looking for a way to break out of these if/else blocks that my code seems stuck in:
function formValidation() {
var form = document.getElementById('project-form');
var username = document.getElementById('username');
var name = document.getElementById('name');
var phone = document.getElementById('phone-number');
var email = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirmation = document.getElementById('password-confirmation');
var submit = document.getElementById('submit-btn');
var errorDisplay = document.getElementById('error-display');
var missingFieldBoolean = false;
var passwordMismatchBoolean = false;
var isUpper = false;
var isNumber = false;
var passwordLength = false;
var validEmail = false;
var createDiv = document.createElement("DIV");
var passwordConstraint, passwordConstraintError;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
//Checks all fields for empty values and updates error div
if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {
missingField = errorDisplay.appendChild(createDiv);
missingField.setAttribute("id", "required-field-error");
missingFieldError = document.getElementById('required-field-error');
missingFieldError.innerHTML = "Missing Fields: ";
if (username.value.length == 0) {
missingFieldError.innerHTML += "Username - ";
}
if (name.value.length == 0) {
missingFieldError.innerHTML += "Full Name - ";
}
if (email.value.length == 0) {
missingFieldError.innerHTML += "Email - ";
}
if (password.value.length == 0) {
missingFieldError.innerHTML += "Password - ";
}
if (passwordConfirmation.value.length == 0) {
missingFieldError.innerHTML += "Password Confirmation - ";
}
} else {
errorDisplay.removeChild(missingFieldError);
missingFieldBoolean = true;
}
//Checks password vs password confirmation to see if they match, else updates error div
if (password.value != passwordConfirmation.value) {
passwordMismatch = errorDisplay.appendChild(createDiv);
passwordMismatch.setAttribute("id", "password-mismatch-error");
passwordMismatchError = document.getElementById('password-mismatch-error');
passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
} else {
errorDisplay.removeChild(passwordMismatchError);
passwordMismatchBoolean = true;
}
//for loop to iterate through password to check for required characters, else updates error div
for (var index = 0; index < password.value.length; index++) {
if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
isUpper = true;
}
if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
isNumber = true;
}
if (password.value.length > 7) {
passwordLength = true;
} else {
passwordConstraint = errorDisplay.appendChild(createDiv);
passwordConstraint.setAttribute("id", "password-constraint-error");
passwordConstraintError = document.getElementById('password-constraint-error');
passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
}
}
//checks if password constraints are met and removes div if true
if (isUpper && isNumber && passwordLength) {
errorDisplay.removeChild(passwordConstraintError);
}
//checks email, if invalid it adds error div, else it removes the div ***NOT WORKING***
if (!(mailformat.test(email.value))) {
invalidEmail = errorDisplay.appendChild(createDiv);
invalidEmail.setAttribute("id", "invalid-email-error");
invalidEmailError = document.getElementById('invalid-email-error');
invalidEmailError.innerHTML = "Please enter a valid email address.";
} else {
errorDisplay.removeChild(invalidEmailError);
validEmail = true;
}
//if all requirements are met and true, submit button becomes enabled ***NOT WORKING***
if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {
submit.disabled = false;
}
}
<div id="error-display"></div>
<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">
<label>Username:</label>
<input id="username" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Full Name:</label>
<input id="name" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Phone Number:</label>
<input id="phone-number" type="tel">
<br>
<label>Email:</label>
<input id="email" type="email" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Password:</label>
<input id="password" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<label>Confirm Password:</label>
<input id="password-confirmation" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<br>
<input id="submit-btn" type="submit" value="Submit" disabled>
</form>
Thanks a lot in advance, and again sorry if i'm breaking the rules.
I would put all the inputs into an object instead, that way you could automatically iterate over the object.
const fieldValues = [
'username',
'name',
'phone-number',
'email',
'password',
'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
return fieldsSoFar;
}, {});
const missingFieldsStr =
Object.entries(fieldValues)
.filter(([, fieldValue]) => fieldValue.length === 0)
.map(([fieldName]) => {
const words = fieldName.split(' ');
const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
return upperWords;
})
.join(', ');
if (missingFieldsStr) {
// display it
}
// skipping some lines...
const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);
And so on.
Don't implicitly create global variables - strongly consider using a linter.
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

Categories

Resources