Can anyone help me with JavaScript form validation? - javascript

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

Related

Password validation is not working in the login form

Password validation is not working in the login form. Here is my code:
function verifyPassword() {
var str = document.getElementById("t1").value;
if (str.match(/[a-z]/g) &&
str.match(/[A-Z]/g) &&
str.match(/[0-9]/g) &&
str.match(/[^a-zA-Z\d]/g) &&
str.length >= 8)
return true;
else
return false;
}
You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.
document.getElementById('t1').addEventListener('change', function() {
if (!verifyPassword()) {
alert("Invalid password");
}
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
if (!verifyPassword()) {
event.preventDefault();
alert("Invalid password");
}
}
Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.
The syntax ?=.*[x] means that you must have the condition x in your string.
Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.
function verifyPassword() {
var str = document.getElementById("t1").value;
var regEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");
if (regEx.test(str) &&
str.length >= 8)
console.log("good")
else
console.log("bad")
}
<div class="txt_field">
<input type="password" id="t1" value="" required>
<label>Password</label>
<button onclick="verifyPassword()">Verify</button>
</div>

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;
}
});

How to use this Javascript checkAlphaNumeric() with HTML?

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>

checking space between text in javascript

I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check the existence of text simply using "if else" statement. But can't do the desired stuff in this way. My code is given below :
<script type="text/javascript">
function checkForm()
{
var cName=document.getElementById("cName").value;
var cEmail=document.getElementById("cEmail").value;
if(cName.length<1)
{
alert("Please enter both informations");
return false;
}
if(cEmail.length<1)
{
alert("Please enter your email");
return false;
}
else
{
return true;
}
}
Name : <input type="text" id="cName" name="cName"/>
<br/>
<br/>
Email : <input type="text" id="cEmail" name="cEmail"/>
<br/>
<br/>
<input type="submit" value="Go!"/>
</form>
Thankyou
Just use the match() method of strings. For example:
'Spaces here'.match(' ');
That returns true.
'Nospace'.match(' ');
That returns false.
So for what you want, just use something like this:
if(cName.match(' ')){
alert('Spaces found!');
return false;
}
Demo
your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word
var b = document.getElementById("cName").value;
var temp = new Array();
temp = b.split(' ');
var count= temp.length;
and if you want to validate your name field that should not use any space
if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
// your code;
}
if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
alert('space found');
}

Categories

Resources