How to use this Javascript checkAlphaNumeric() with HTML? - javascript

I am stumped. I have the following code and cannot get it to work right. I'm kind of using a password or email validation event of onkeyup, but I really just want it to work if I click on submit. My form is already using validateForm() and checkPass(). I just need to get this to work.
// *********** ALPHA-Numeric check ***************************
function checkAlphaNumeric()
{
var passw = document.getElementById("_password");
var mystring=new String(passw)
var authpassword = document.getElementById("AuthPass");
if(mystring.search(/[0-9]+/)==-1) // Check at-least one number
{
authpassword.innerHTML = "<span class='smaller'>*Password must be 8 characters, 1 letter, and 1 number!</span>!";
return false;
} else {
count++;
document.getElementById("err_password").innerHTML="";
}
if(mystring.search(/[A-Z]+/)==-1 && mystring.search(/[a-z]+/)==-1) // Check at-least one character
{
authpassword.innerHTML = "<span class='smaller'>*Password must be 8 characters, 1 letter, and 1 number!</span>!";
return false;
} else { count++;
document.getElementById("err_password").innerHTML="";
}
} //*** END FUNCTION
HTML CODE IS BELOW
<input id="_password" type="password" name="password" autocomplete="off" size="40" onkeyup="checkAlphaNumeric(); return false;"><span id="AuthPass" class="AuthPass" style="font-size: smaller; color:red;""></span>

Related

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Form Validation Vanilla JS

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.
What I Want to Do:
(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.
(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.
What I Have Done
(1) Created a mini version of the form with two inputs:
One that takes a first name, a space and a last name
One that takes a phone number set up the following way xxx xxx xxx
(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.
Where I am Stuck:
I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.
What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.
function checkForm()
{
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
function checkFirstName()
{
if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
console.log("Put a first Name and Last Name");
}
else
{
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber()
{
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
{
console.log("Please Put in a proper phone number");
}
else
{
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
};
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
See below code.
It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.
function checkForm() {
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var phoneCanSubmit, nameCanSubmit = false;
function checkFirstName() {
if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
nameCanSubmit = false;
console.log("Put a first Name and Last Name");
} else {
nameCanSubmit = true;
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber() {
if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
phoneCanSubmit = false;
console.log("Please Put in a proper phone number");
} else {
phoneCanSubmit = true;
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
if (nameCanSubmit && phoneCanSubmit) {
document.getElementById("myButton").disabled = false;
} else {
document.getElementById("myButton").disabled = true;
}
};
<form>
First Name:
<input type="text" id="name" onblur="checkForm()" />
<label id="nameErrorPrompt"></label>
<br />Phone Number:
<input type="text" id="phone" onblur="checkForm()" />
<label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.
window.addEventListener('load', function(e) {
var nameInput = document.getElementById('name');
var phoneInput = document.getElementById('phone');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(e) {
e.preventDefault(); //Stop the page from refreshing
getNextPage('Next page shown!!');
}, false);
nameInput.addEventListener('blur', function(e) {
checkName(this.value);
}, false);
phoneInput.addEventListener('blur', function(e) {
//Uncomment below to make this responsible only for checking the phone input
//checkPhoneNumber(this.value);
/*You could do away with diasbling and check the form
on submit, but if you want to keep the disable logic
check the whole form on the blur of the last item*/
checkForm();
}, false);
}, false);
function getNextPage(foo) {
console.log('Callback fired: ', foo);
//Do something here
}
function checkPhoneNumber(phone) {
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
console.log("Please Put in a proper phone number");
return 0;
}
else {
console.log("Thank you name entered");
return 1;
}
};
//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
console.log("Put a first Name and Last Name");
return 0;
}
else {
console.log("Thank You phone entered");
return 1;
}
};
function checkForm() {
var validCount = 0;
fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
var phoneNum = document.getElementById('phone').value;
var name = document.getElementById('name').value;
var myButton = document.getElementById('myButton');
validCount += checkPhoneNumber(phoneNum);
validCount += checkName(name);
console.log(validCount + ' of ' + fieldCount + ' fields are valid');
if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs
myButton.disabled = false;
}
else {
myButton.disabled = true;
}
}
HTML
<form>
First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
How about you start by making the onblur for each input return a boolean indicating if the field is valid.
Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.
If you really want the button to enable you can use the same pattern, but do
document.getElementById("myButton").disabled = !canSubmit;
and you will always want to call checkForm on field blur like you are now.
Also note you aren't scoping canSubmit locally right now.

Can anyone help me with JavaScript form validation?

I have created a validate function using JavaScript. I need a validation that tests that password field in a form to make sure it is:
At least 8 characters.
Contains a numeric value.
Contains an alphabetic value.
I just need an If statement inside my validate function
function Validate()
{
with(document.memberInfo) {
evt = new userInfo(username.value, password.value, email.value, firstname.value, lastname.value, age.value, description.value);
}
with(evt)
{
if((email.indexOf("#",0)==-1))
{
alert("The email must contain the # symbol.");
return false;
}
evt.printEvent();
}
return true;
}
using regx function you can validate ur form . here is the code .
var xstr="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$";
var str=Document.getElementById("id").value;
var ck=xstr.exec(str);
if(!ck || ck[0]!=str){
//code
}
you can use regex "/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/" refer this link stackoverflow
JsFiddle
var regex = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
<input type="text" id="myinput" value="vexillology"/>
<button id="testBtn" onclick=test()>test</button>
<button id="matchBtn" onclick=match()>match</button>
Using regex is the way to go, but the more readable solution is probably:
function isValid(pass) {
return pass.length >= 8 && // at least 8 characters
/\d/.test(pass) && // contains a digit
/[A-Za-z]/.test(pass); // contains a letter
}
function isValid(pass) {
return pass.length >= 8 &&
/\d/.test(pass) &&
/[A-Za-z]/.test(pass);
}
var field = document.getElementById("password");
var output = document.getElementById("output");
field.onkeyup = function() {
output.innerHTML = isValid(field.value) ? "Valid" : "Not Valid";
}
<input type="text" id="password" placeholder="Enter password" />
<span id="output"></span>
Alternatively, you can put it all in one regex:
function isValid(pass) {
return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(pass);
}
JSFiddle

javascript validation numerical

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}
You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>
Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

Categories

Resources