JavaScript/ Alphanumeric validation not working - javascript

I have this reg ex for alphanumeric validation that I got from this post
but it is not working with this function (I have a similar function for email and it works)
function checkName(field) {
var x = document.getElementById(field).value;
var y = /^[a-z0-9]+$/i;
//var z = /^[0-9]*$/;
if (x == "" || !x.match(y) ) {
alert("Invalid character");
if (x.length <= 2 || x.length >= 15) {
alert("Insert a name between 3 and 15 characters");
}
return false;
}
}
If I write some string/name I get both alerts. Can someone tell me what is wrong with this function?

Below is the approach for alphanumeric validation:
function checkName(field)
{
var x = document.getElementById(field).value;
if (x.length <= 2 || x.length >= 15)
{
alert("Insert a name between 3 and 15 characters");
return false;
}
var y = /^[0-9a-zA-Z]+$/;
if (x == "" || !x.match(y) )
{
alert("Invalid character");
return false;
}
alert("ALL OK");
return true;
}
<input type="text" id="textName" />
<button onClick="checkName('textName');">Check</button>
The Regex check for capital and small alphabets and numbers, and also checks for the length.

Your code works for me
function checkName(field) {
console.log(field);
var x = field;
var y = /^[a-z0-9]+$/i;
if (x == "" || !x.match(y) ) {
console.log("Invalid character");
}
if (x.length <= 2 || x.length >= 15) {
console.log("Insert a name between 3 and 15 characters");
}
}
//valid
checkName('testdskfjskdlf');
//invalid
checkName('slkjf*%');
//too long
checkName('jjjjjjjjjjjjjjjjjjjjjjjjjjj');

Related

HTML/JavaScript Validation Issues

Part of a website I'm building I'm trying to validate the registration from. The code works it's just once it gets to validating the firstname it seems to quit and return true.. I'm lost on how to fix it as I haven't encountered this issue before and I cannot see anything wrong with my code..
function validateForm(){
var x = document.registration.email.value;
var atPos = x.indexOf("#");
var dotPos = x.lastIndexOf(".");
if(document.registration.user.value.length < 4){
window.alert("Please enter a valid username. (4 - 20 Characters)");
document.registration.user.focus();
return false;
}
if(document.registration.pass.value.length < 4){
window.alert("Please provide a valid password. (4 - 50 Characters)");
document.registration.pass.focus();
return false;
}
if(atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= x.length) {
window.alert("Invalid email format.");
document.registration.email.focus();
return false;
}
if(document.registration.firstname.value.length < 3){
window.alert("Please provide a valid firstname. (3 - 20 Characters)");
document.registration.fistname.focus();
return false;
}
if(document.registration.surname.value.length < 3){
window.alert("Please a valid surname. (3 - 20 Characters)");
document.registration.surname.focus();
return false;
}
if(document.registration.country.value.length < 3){
window.alert("Please provide valid Country. (3 - 20 Characters)");
document.registration.country.focus();
return false;
}else{
return true;
}
}
<form name="registration" action="registration.php" method="post" onsubmit="return validateForm()">
You have a typo for the firstname field:
document.registration.fistname.focus();
You can check your browser's element inspector for any javascript errors after submitting the form.
its returning true only if your conditional for country is met. try using if else if and else
function validateForm(e){
e.preventDefault();
var x = document.registration.email.value;
var atPos = x.indexOf("#");
var dotPos = x.lastIndexOf(".");
if(document.registration.user.value.length < 4){
window.alert("Please enter a valid username. (4 - 20 Characters)");
document.registration.user.focus();
return false;
}
else if(document.registration.pass.value.length < 4){
window.alert("Please provide a valid password. (4 - 50 Characters)");
document.registration.pass.focus();
return false;
}
else if(atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= x.length) {
window.alert("Invalid email format.");
document.registration.email.focus();
return false;
}
else if(document.registration.firstname.value.length < 3){
window.alert("Please provide a valid firstname. (3 - 20 Characters)");
document.registration.fistname.focus();
return false;
}
else if(document.registration.surname.value.length < 3){
window.alert("Please a valid surname. (3 - 20 Characters)");
document.registration.surname.focus();
return false;
}
else if(document.registration.country.value.length < 3){
window.alert("Please provide valid Country. (3 - 20 Characters)");
document.registration.country.focus();
return false;
}else{
return true;
}
}

I don't want to allow a 9 digit number in my textbox which is in format:123-12-1234 or 123456789

I am trying like this:
function k(){
var x = $('#textArea').val();
for (i = 0; i < x.length; i++)
{
if(x[i].match(/^[0-9]/))
{
if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
{
if(x[i+11].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
{
if(x[i+9].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
return 'true';
}
Or simply
var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
Or if you only want to allow - and digits
var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length )
{
return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
or using pure regexp
to match the 123-45-678 and 12345678 formats:
var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
return true;
} else return false;
to match any number less then 9 digits:
var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
return true;
} else return false;

why is my javascript not working on my php page?

I am facing issue with javascript for form validation.
On one of the forms the javascript function is working properly, and when on other form, i am trying to do form validation, but the script does not fire up.. i have tried many times to clear my browser cache and refreshed the page but i am not getting any results.
I would be thankful if anyone reviews it and help spot the issue.
The following is the function that works on my homepage:
<script>
function validate()
{
var uid = document.getElementById("usrname").value;
var pwd = document.getElementById("passwd").value;
if (uid == "" || pwd == "") {
alert("Empty fields not allowed");
return false;
}
else if (uid.length < 4 || uid.length > 20) {
alert("User ID string length should be between 4 - 20");
return false;
}
else if (pwd.length < 6 || pwd.length >20) {
alert("Password length should be between 6 - 20");
return false;
}
return true;
}
</script>
<form name="ulogin" action="login.php" method="post" onSubmit="return validate();">
The following validation code on the other page does not run:
<script>
function regval()
{
var cname = document.getElementById("name1").value;
var email = document.getElementById("email").value;
var phn = document.getElementById("phone").value;
var addr1 = document.getElementById("addr1").value;
var addr2 = document.getElementById("addr2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var uname = document.getElementById("uname").value;
var pwd = document.getElementById("passwd").value;
var cnfp = document.getElementById("cnf_passwd").value;
var secans = document.getElementById("sec_ans").value;
var regex=/^[0-9]+$/;
var alphanum=/^[a-z0-9]+$/i;
if(cname == "" || email == "" || phn == "" || addr1 == "" || addr2 == "" || city == "" || state == "" || state == "" || country == "" || uname == "" || pwd == "" || cnfp == ""|| secans == "") {
alert("Empty fields not allowed");
return false;
}
if (cname.length < 3 || cname.length > 20) {
alert("Name length should be between 4-20 characters.");
return false;
}
if (email.length < 10 || email.length > 50 ) {
alert("email length should be between 10-50 characters.");
return false;
}
if (phn.length < 7 || phn.length > 11 ) {
alert("check phone number length.");
return false;
}
else if (!phn.match(regex)) {
alert("Please check inputs, only numbers are allowed.!");
return false;
}
if (city.toLowerCase() != "surat" || state.toLowerCase() != "gujarat" || country.toLowerCase() != "india") {
alert("Sorry, we only serve in surat currently at the moment..!!");
return false;
}
if (uname.length < 4 || uname.length > 20) {
alert("user name should be between 4 - 20 characters.");
return false;
}
else if (!uname.match(alphanum)) {
alert("only characters A-z 0-9 are allowed.");
return false
}
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
if (pwd != cnfp) {
alert("the passwords do not match, please check and try again.");
return false;
}
if (secans.length < 5 || secans.length > 20) {
alert("please check for security answer length. It should be between 5 to 20 characters.");
return false;
}
return true;
}
</script>
<form name="usreg" action="signup.php" method="POST" onSubmit="return regval();">
the script tags are in the head tags of my webpage.
Thanks in advance.
Missing closing bracket ) Here else if (!pwd.match(alphanum) {
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Should be
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum)) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Note: Always check browser console log for errors.

javascript cell number validation

I want to validate cell number using JavaScript.
Here is my code.
if(number.value == "") {
window.alert("Error: Cell number must not be null.");
number.focus();
return false;
}
if(number.length != 10) {
window.alert("Phone number must be 10 digits.");
number.focus();
return false;
}
Here is the issue, when I submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.
When I submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. It is also fine.
The problem is when I submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.
Please help me.
Thank You.
And also need the validation code for only digits for cell number.
If number is your form element, then its length will be undefined since elements don't have length. You want
if (number.value.length != 10) { ... }
An easier way to do all the validation at once, though, would be with a regex:
var val = number.value
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
number.focus()
return false
}
\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.
function IsMobileNumber(txtMobId) {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMobile = document.getElementById(txtMobId);
if (mob.test(txtMobile.value) == false) {
alert("Please enter valid mobile number.");
txtMobile.focus();
return false;
}
return true;
}
Calling Validation Mobile Number Function HTML Code -
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Please enter only Numbers.");
return false;
}
return true;
}
function ValidateNo() {
var phoneNo = document.getElementById('txtPhoneNo');
if (phoneNo.value == "" || phoneNo.value == null) {
alert("Please enter your Mobile No.");
return false;
}
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");
return false;
}
alert("Success ");
return true;
}
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />
<input type="button" value="Submit" onclick="ValidateNo();">
If you type:
if { number.value.length!= 10}...
It will sure work because the value is the quantity which will be driven from the object.
This function check the special chars on key press and eliminates the value if it is not a number
function mobilevalid(id) {
var feild = document.getElementById(id);
if (isNaN(feild.value) == false) {
if (feild.value.length == 1) {
if (feild.value < 7) {
feild.value = "";
}
} else if (feild.value.length > 10) {
feild.value = feild.value.substr(0, feild.value.length - 1);
}
if (feild.value.charAt(0) < 7) {
feild.value = "";
}
} else {
feild.value = "";
}
}
Verify this code :
It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}
<script type="text/javascript">
function MobileNoValidation()
{
var phno=/^\d{10}$/
if(textMobileNo.value=="")
{
alert("Mobile No Should Not Be Empty");
}
else if(!textMobileNo.value.match(phno))
{
alert("Mobile no must be ten digit");
}
else
{
alert("valid Mobile No");
}
}
</script>
I used the follow code.
var mobileNumber=parseInt(no)
if(!mobileNumber || mobileNumber.toString().length!=10){
Alert("Please provide 10 Digit numeric value")
}
If the mobile number is not a number, it will give NaN value.
<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>

How to validate multiple fields at the same time using JQuery

I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.

Categories