I have some javascript written to validate that a string is alphanumeric but i was just wondering how i could add some code to include hyphens(-) and slash's(/) as acceptable inputs. Here is my current code:
function validateAddress() {
var address = document.getElementById('address');
if (address.value == "") {
alert("Address must be filled out");
return false;
} else if (document.getElementById('address').value.length > 150) {
alert("Address cannot be more than 150 characters");
return false;
} else if (/[^a-zA-Z0-9\-\/]/.test(address)) {
alert('Address can only contain alphanumeric characters, hyphens(-) and back slashs(\)');
return false;
}
}
Simply add them to the character group. Of course, because both - and / are special characters in this context (/ ends a RegExp, - expresses a range), you'll need to escape them with a preceding \:
function validateAddress(){
var TCode = document.getElementById('address').value;
if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
function isValidCharacter(txtTitle) {
var title = document.getElementById(txtTitle);
var regExp = /^[a-zA-Z]*$/
if (!regExp.test(title.value)) {
title.value = '';
return false;
}
else {
return true;
}
}
function Validation(){
var txtTitles = document.getElementById('txtTitle');
if (isValidCharacter(txtTitles.id) == false) {
alert("Please enter valid title. No special character allowed.");
return false;
}
}
$("#Btn").unbind("click").click(function () {
if (Validation() == false) {
}
else {
//success
}
}
Input:
<input type="text" name="textname" id="tname" onblur="namefun(this.value)">
Javascript
function namefun(c) {
var spch = /[A-z\s]/gi;
var dig = /[0-9]/g;
var ln = c.length;
var j = 1;
for (var i = 0; i < ln; i++) {
var k = c.slice(i, j);
if (spch.test(c) == false || dig.test(c) == true) {
alert("Invalid name");
document.getElementById("tname").value = "";
ln = 0;
setTimeout(function () {
tname.focus();
}, 1);
//return false;
}
j++;
}
}
Simple Javascript Version
isValidCharacter(text) {
const validCharacterRegex = /^[a-zA-Z]*$/;
return validCharacterRegex.test(text);
}
Typescript Version
isValidCharacter(text: string): boolean {
const validCharacterRegex: RegExp = /^[a-zA-Z]*$/;
return validCharacterRegex.test(text);
}
<?php
if(isset($_POST["Password"]))
{
$servername="localhost";
$username="root";
$password="";
$dbname="coustomer";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("connection failed:" .mysqli_connect_error());
}
$UserID= $_POST["Userid"];
$Password= $_POST["Password"];
$sql= "SELECT Name, Contact, Email, UserID, Password FROM coustomers WHERE UserID ='$UserID' password='$Password' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo '<script>alert("Login successfully")</script>';
}
{
else
{
echo "No record found";
}
}
?>
Related
I'm trying to apply form validation using js,the problem I'm facing is the form always submits no matter what errors are shown in the form.
the form contains 6 fields: username,email,password,retype_pass, first_name,last_name.
the js code is like this:
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
Download the js file here : https://onionfiles.com/file/HGGaFR2G
and include it in, then try this
$().ready(function() {
// validate form on keyup and submit
$("#FORMID").validate({
rules: {
username: "required",
email: "required",
password: "required",
retype_pass: {
required: true,
equalTo:"#password"
}
first_name: "required",
last_name: "required"
},
messages: {
username: "Please enter Username",
email : "Please enter a valid Email",
password: "Please enter a password",
retype_pass: {
required: "Please confirm your password",
equalTo: "Please enter the same password as above"
},
first_name: "Please enter first name",
last_name: "Please enter last name"
}
});
});
A quick fix from your code will be the following.
(function() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
$("#formId").on("submit", checkForBlank);
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
username_err = false;
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
//var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
var re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
pwd_err_msg = false;
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2 || pass2.length === 0) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
confirm_pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
confirm_pwd_err_msg = false;
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
email_err = false;
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
fname_err = false;
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
lname_err = false;
}
}
}
function checkForBlank(e) {
check_userName();
check_email();
check_pwd();
check_pwd_conf();
check_fname();
check_lname();
if(username_err || email_err || pwd_err_msg || confirm_pwd_err_msg || fname_err || lname_err) {
e.preventDefault();
}
}
}());
I have changed the checkForBlank function. I have attached it to the form submit event and checked for any errors inside it. Then prevented form submission if any errors found.
But I think the whole code needs to be refactored to reduce code duplication.
Update:
I have made changes to the above code. Here is the working jsfiddle.
I need to know if a string contains a character (one or multiple times) at any point of the string.
For example with the character "&":
"&hfds" is invalid, "%$/&h&" is invalid etc.
Im doing this as part of a password validation:
function applySpecialCharacterFilter(password) {
if (password.match(/([!,%,#,#,$,^,*,?,_,~])/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
in the first part it checks of the password contains any of the allowed characters, and then increments the value of the validation. But then passwords containing not allowed characters can pass.
With the else if im trying to catch it, but it only works if its not in a special character sequence like $%&
Thank you
Edit:
Here is the whole function:
function checkStrength(password){
var strength = 0;
var passwordMessage = $('#passwordMessage');
if (password.length == 0) {
result.removeClass();
return '';
}
if (password.length < 6) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too short';
} else if(password.length > 8) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too long';
} else {
strength += 1;
}
try {
strength += applyLowerAndUpperCaseFilter(password);
strength += applyNumbersAndCharactersFilter(password);
strength += applySpecialCharacterFilter(password);
strength += applyTwoSpecialCharacterFilter(password);
strength += applyAlphabeticalCharacterCriteria(password);
} catch(error) {
validPassword = false;
result.removeClass();
result.addClass('short');
passwordMessage.html('').append('<p>TPassword contains invalid characters!</p>');
return 'Invalid';
}
passwordMessage.html('');
if (strength <= 2) {
validPassword = false;
result.removeClass();
result.addClass('weak');
return 'Schwach';
} else if (strength <= 3 ) {
validPassword = true;
result.removeClass();
result.addClass('good');
return 'Good';
} else {
validPassword = true;
result.removeClass();
result.addClass('strong');
return 'Strong';
}
}
function applyLowerAndUpperCaseFilter(password) {
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
return 1;
return 0;
}
function applyNumbersAndCharactersFilter(password) {
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
return 1;
return 0;
}
function applySpecialCharacterFilter(password) {
if (password.match(/^([!%##$^*?_~]+)$/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
function applyTwoSpecialCharacterFilter(password) {
if (password.match(/(.*[!,%,#,#,$,^,*,?,_,~].*[!,",%,#,#,$,^,*,?,_,~])/))
return 1;
else if(password.match(/([&])/))
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
return 0;
}
function applyAlphabeticalCharacterCriteria(password) {
var quality = 0;
var sequences = [
'abcdefghijklmnopqrstuvwxyz',
'01234567890',
'!\"§$%/()=?'
];
var proceed = true;
for(var i=0; i<(password.length-3); i++) {
for(var index = 0; index < sequences.length; index++) {
var needle = password.substring(i, 3);
if(stripos(sequences[index], needle) != false) {
quality -= 1;
proceed = false;
}
if(proceed == false) break;
}
if(proceed == false) break;
}
return quality;
}
function stripos(f_haystack, f_needle, f_offset) {
var haystack = (f_haystack + '')
.toLowerCase();
var needle = (f_needle + '')
.toLowerCase();
var index = 0;
if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
return index;
}
return false;
}
The messages and classes are for real time validation output only.
Rules:
The Password needs to be between 6 and 8 characters long.
It has to have at least 1 upper and 1 lower case character.
It has to have numbers.
It has to have at leats 1 special characters (2 give more value).
Only these special characters are allowed - _ . : , ; ! # § $ % / = ? #
The characters should not appear in a sequence if possible, so no abc,123,!§$ etc.
You have to anchor the first regex and add a quantifier:
if (password.match(/^([!,%,#,#,$,^,*,?,_,~]+)$/)) {
// here ^ ^ ^
The comma is not mandatory except if you want to match it:
if (password.match(/^([!%##$^*?_~]+)$/)) {
You can use indexOf method:
function applySpecialCharacterFilter(password) {
if (password.indexOf('&')>-1) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
if (password.match(/^([!,%,#,#,$,^,*,?,_,~]+)$/)) {
return 1;
}
return 0;
}
and you need to change your Regexp according #M42 answer
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.
These two Javascript functions are supposed to convert serial numbers (2-9999) for example into a number , but the functions below are not working for some reason .. they were originally written in PHP ... Works in PHP but not for Javascript.
<html>
<head>
<script type="text/javascript">
function my_isnum(str, negative=false, decimal=false)
{
var has_decimal = false;
var len = strlen(str);
if (len > 0) {
var valid = true;
for (var i=0; valid && i < len; i++) {
if (!(str[i] >= "0" && str[i] <= "9")) {
if (str[i] == "-") {
if (!negative || i != 0) {
valid = false;
}
} else if (str[i] == ".") {
if (!decimal || has_decimal) {
valid = false;
}
} else {
valid = false;
}
}
}
} else {
valid = false;
}
return valid;
}
function esn_to_num(esn) {
var tmp = [];
if ((tmp = esn.split("-")) {
if (tmp.length == 2
&& my_isnum(tmp[0])
&& my_isnum(tmp[1])
) {
esn = ((tmp[0] << 23) | tmp[1]);
} else {
esn = -1;
}
} else {
esn = -1;
}
return esn;
}
alert(2-9999);
</script> </head>
</html>
Original PHP functions
<?php
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
?>
There is no such thing as strlen in Javascript. Use str.length instead.
Also, as Jason Sperske suggested below, change this:
function my_isnum(str, negative=false, decimal=false)
To this:
function my_isnum(str, negative, decimal)
{
if (typeof negative == "undefined") negative = false;
if (typeof decimal == "undefined") decimal = false;
....
}
These two javascript functions are supposed to convert serial numbers (2-9999) for example into a number.
Why not just get rid of the - and parse as a decimal number?
function padToFourDigits(_, digits) {
return "0000".substring(digits.length) + digits;
}
function serialToNum(serialNumStr) {
return +(serialNumStr.replace(/-(\d{1,4})/g, padToFourDigits));
}
Then
serialToNum('2-9999') === 29999
serialToNum('2-999') === 20999
I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!