validation fails on submit - javascript

The code should validate that the input fields dont contain a number and only letters and also both fields arent blank. Currently it works with detecting if they aren't blank but it only detects a number in 'firstname' - I have managed to get one or the other working but never both at the same time. Help!!
Also, If the validation fails the joke shouldn't be returned (the button onclick provides the joke by using the first and last name and sending it to an api to retrieve the joke).
function validateForm() {
var firstname = document.getElementsByName("firstname")[0].value;
var lastname = document.getElementsByName("lastname")[0].value;
var input = document.getElementsByName("firstname" && "lastname");
if (firstname == "" && lastname == "") {
alert("Please enter atleast one name");
}
else if (!(/^[a-zA-Z]+$/.test(firstname || lastname))) {
alert("'Only alphabets allowed'");
}
}
return (
<div className="jokeForm" >
<form name="searchForm" >
<input type="text" name="firstname" placeholder="First name" value={firstname} onChange={(e) => setFN(e.target.value)} />
<input type="text" name="lastname" placeholder="Last name" value={lastname} onChange={(e) => setLN(e.target.value)} />
</form>
<button onClick={() => validateForm(newJoke(firstname, lastname))}>click here for a personalised chuckle</button>
<h3>{joke}</h3>
</div >
)
}

Use + to add both strings together. And do test with Regex. eg.
var firstname="j";
var lastname="k1";
if (!(/^[a-zA-Z]+$/.test(firstname + lastname))) {
alert("Only alphabets allowed!");
}

Related

passoword validation without jQuery

I am making a password validation using js and html. It suppose to show certain information under the input parts if the input is not valid. But whatever the input is, there's no message at all. I am not sure which part I did wrong. Code is posted below
var name = document.getElementById("userName");
var passWord = document.getElementById("passWord");
var flag;
function check() {
flag = validateInput(name, passWord);
if (flag)
isPaswordValid(passWord);
if (flag)
ispassWordStrong(passWord);
}
function validateInput(name, passWord) {
if (name.length = 0 || passWord.length < 0) {
document.getElementById("errorMessage").innerHTML = "Please enter Username and passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check Username and passWord are valid
function isPaswordValid(passWord) {
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
//Check passWord is valid or not and having length of passord should not less than 8
if (passWord.length < 8 || (!re.test(passWord))) {
document.getElementById("errorMessage").innerHTML = "Invalid passWord. Please enter new passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check password has no more than 3 characters from username in passWord
function ispassWordStrong(userName, passWord) {
var n = 0;
for (var i = 0; i < userName.length; i++) {
if (passWord.indexOf(userName[i]) >= 0) {
n += 1;
}
}
if (n > 3) {
document.getElementById("errorMessage").innerHTML = "passWord can't contain more than 3 characters from the username.";
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
}
}
});
<body>
<fieldset>
<legend>Password Validator</legend>
User Name:
<input type="text" id="userName" name="userName" placeholder="User Name" onkeyup='check();' /><br>
passWord:
<input type="password" id="passWord" name="passWord" placeholder="Password" onkeyup='check();' />
<input type="submit" id="inputValidate" value="Validate"><br /><br />
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
</body>
Sorry for the long codes and thanks for your help.
The following should do what you require:
// collect all DOM elements in object ti: ti.i, ti.e, ti.u, ti.p
const ti=["inputValidate","errorMessage","userName","passWord"]
.reduce((a,c)=>(a[c.substr(0,1)]=document.querySelector('#'+c),a),{});
// delegated event listening for event "input":
document.querySelector('fieldset').addEventListener('input',ev=>{
if (Object.values(ti).indexOf(ev.target)>1){ // for userName and passWord do ...
let u=ti.u.value.toLowerCase();
ti.e.textContent= (ti.p.value.length > 2
&& ti.p.value.split('').reduce((a,c)=>a+=u.indexOf(c.toLowerCase())>-1?1:0,0) > 2 )
? "The password contains at least 3 letters from the username!" : "";
}})
// event listening for button click on "validate":
ti.i.addEventListener('click',ev=>!(ti.e.textContent=
(ti.u.value.trim().length ? "" : "User name is empty.") ||
(ti.p.value.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)
? "" : "The password is not complex enough!" )))
<fieldset>
<legend>Password Validator</legend>
User Name:<br/>
<input type="text" id="userName" name="userName" placeholder="User Name"/><br>
passWord:<br/>
<input type="password" id="passWord" name="passWord" placeholder="Password"/>
<input type="submit" id="inputValidate" value="Validate"><br/>
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
While inputting characters in the fields #userName and #passWord it checks for the occurence of user name characters in the password. This is done ignoring upper or lower case. And when clicking on the "validate" button the complexity of the password is checked against the regular expression /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/. This regular expression demands at least
one upper case chraracter,
one lower case character
one number and
a minimum length of 8.
There is also a rudimentary check on the user name. It must contain at least one non-blank character. The event handler for the click event on the "validate" button returns false whenever an error is detected. This can be used to prevent the submission of the form. However, the form itself was not supplied by OP.

How to split string of input tag HTML?

When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>

if contact number is both empty and does not have 11 digits

id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link

Form onSubmit validation not working

I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>

Check to see if at least one input field out of many has a value

I have 4 input fields and I want to check to see if at least 1 has a value. If none have values I want to return.
Here is what I have and I know if doesn't work because it doesn't enter the if statement if nothing has been entered.
if ($('#Name').val() != "" && $('#State').val() != "" && $('#City').val() != "" && $('#Zip').val() != "") {
showAlert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
return;
}
if none have a value I want to show a message and return without further processing.
So instead of checking that the value is not empty you should check that they ARE empty:
if (!$('#Name').val() && !$('#State').val() && !$('#City').val() && !$('#Zip').val()) {
return alert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
}
You can also put the alert after the return to make it shorter.
Fiddle
You can select all the inputs type text and filter them checking for the value being present:
$(function () {
$("#Check").on("click", function () {
// Will return the inputs containing value.
var anyValue = $("input[type=text]").filter(function () {
return $(this).val().trim() !== "";
});
// If there's at least one containing any value.
console.log(anyValue.length !== 0);
});
});
I considered the markup below:
<input name="Name" id="Name" type="text" placeholder="Name" />
<input name="City" id="City" type="text" placeholder="City" />
<input name="State" id="State" type="text" placeholder="State" />
<input name="Zip" id="Zip" type="text" placeholder="Zip" />
<button id="Check">Check</button>
Demo

Categories