I have the following JavaScript code that is working:
<script>
function validate(form) {
// Shortcut to save writing
var pwd = form.elements.lgps.value;
// Check length
if(8 > pwd.length || pwd.length > 16)
return false;
// Check for at least 1 lowercase letter
var rgx = /[a-zA-Z]+/;
if(!rgx.test(pwd))
return false;
// Check for at least 1 digit
rgx = /\d+/;
if(!rgx.test(pwd))
return false;
// Check for no spaces
rgx = /\s/;
if(rgx.test(pwd))
return false;
return true;
}
</script>
And here's my form:
<form method="post" action="406.php" language="javascript"
name="myform" id="myform" onsubmit="return validate(this);">
I would like to add a message alert if all the above fails, and also another field in my form to validate. So basically I have a username field and a password field.
I want the password field to be between 8 and 20 characters long, and contain at least 1 digit.
That looks fine, besides the fact that the first regexp tests for uppercase and lowercase, just bracket the if statements and add
alert('Password not right')
before the return statement.. obviously for each return you can change the alert accordingly.
Included below is a solution that utilizes jQuery and stores the validation requirements into an object named tests.
The value provided from the desired element, in this case the input with an ID of pass, is checked against the tests declared in each property. If the test passes, then that property is set to 1 to indicate true. If the test fails, then the property is set to 0 to indicate false.
The object is then traversed to check which properties passed and which ones failed. If at least one test failed, then an alert() message is used to notify the user of the invalid criteria.
HTML:
<input type="text" id="pass" />
jQuery:
function validatePassword(pwd) {
var errors = [];
var tests = {
'- Min/Max Length of 8-16 characters': function(){
return (pwd.length < 8 || pwd.length > 16 ? 0 : 1);
}(),
'- Contains Alpha-numeric characters': function(){
rgx = /[a-zA-Z]+/;
return (!rgx.test(pwd) ? 0 : 1);
}(),
'- Contains 1 or more Digits': function(){
rgx = /\d+/;
return (!rgx.test(pwd) ? 0 : 1);
}(),
'- Contains No Spaces': function(){
rgx = /\s/;
return (rgx.test(pwd) ? 0 : 1);
}()
};
for(result in tests ){
if(tests[result] == 0){
errors.push(result);
}
}
if(errors.length > 0){
alert('Please correct your password to meet the following criteria:\n' + errors.join('\n'));
}
}
$(function(){
$('#pass').blur(function(){
validatePassword($(this).val());
});
});
Demo: http://jsfiddle.net/Rmm6d/
function validatePwd(form) {
var pwd = form.elements.lgps.value;
if(8 > pwd.length || pwd.length > 16){
alert("Your password must be 8-16 characters in length");
return false;
}
var rgx = /[a-zA-Z]+/;
if(!rgx.test(pwd)){
alert("Your need at least 1 lowercase letter");
return false;
}
rgx = /\d+/;
if(!rgx.test(pwd)){
alert("You need at least 1 digit");
return false;
}
rgx = /\s/;
if(rgx.test(pwd)){
alert("You can't have spaces");
return false;
}
return true;
}
function validateUnm(form){
var unm = form.elements.lgem.value;
if(3 > unm.length || unm.length > 20){
alert("Your username must be 3-20 characters in length");
return false;
}
//and more conditions....
return true;
}
You would call this by:
<form onsubmit="validatePwd(this);validateUnm(this)">
Related
I need to validate Textbox for this test cases.
It will allow 0 to 59 no characters and special character not allowed except *,/
It will allow 1,2,3,4 but 1,2,3,60 should not allow
It will allow /59 or 1,2,3,4,/59 but 1,2,3,5,*/59/19 should not allow
i tried,
var input = document.getElementById('configMinute').value;
//console.info("Else Called");
var slashPattern = "/";
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var getStringCheck = checkSpecialChar(input,specialChars);
if(getStringCheck==true){
// string = 1,2,3,*/10
// ,*/
var getStringValues = input.split(',');
var notAllowedCharPattern = "<>#!#$%^&()_+[]{}?:;|'\"\\.~`-=";
var allowedChar = checkSpecialChar(input,notAllowedCharPattern);
if(allowedChar==false){
console.info(getStringValues);
getStringValues.forEach(function(element){
//string = 1 2 3 */10
var validateSlash = checkSpecialChar(element,slashPattern);
if(element.startsWith("*")==true){
var newInput = element.split('/');
console.info("newInput: "+ element);
newInput.forEach(function(element) {
console.info("newInput Foreach: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}
else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
});
}else{
console.info("* Else: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
}
});
}else{
alert ("File name has special characters \nAllowed Characters are *,/ ==>3");
document.getElementById('configMinute').focus();
return false;
}
}else if(input == '*' || (input>=0 && input <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>4");
document.getElementById('configMinute').focus();
return false;
}
Thanks in advance
You could try a regex like
(?:(?:^|,)(?:[1-5]?\d|\*?\/59)\b)+$
It matches the beginning of the line (^) or a , followed by either a number, 0-59, or /59 optionally preceded by a *. And this pattern can then repeat any number of times, until the end of the line.
See it here at regex101.
I'm currently using JavaScript code to validate a text field when the user types in letters a-z.
The script shows a tick if this is valid and a cross if its not. Now I am trying to add to the code to say check that the letters meet a minimum length of at least 4 characters, and if the min characters is met then show the tick and if the text is under the min character length show the cross.
How can I adjust my script to check the minimum length of the characters entered? Also can someone show me how I can allow '-' to be allowed in my validation?
script:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
if (reg.test(CnameField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
tried:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false)
if(input.value.length>!=len.min) return flase;
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
Almost there but you have a few syntax issues, so I've created an example test script for you:
function validateValue(value) {
var reg = /^[A-Za-z]+$/g;
var len = {min:4,max:60};
if (!reg.test(value)) {
console.log('didn\'t match regex');
return false;
}
if (value.length < len.min || value.length > len.max) {
console.log('incorrect length: ' + value);
return false;
}
console.log('correct length: ' + value);
return true;
}
validateValue('teststring');
Notice how I have set up the regex test, removing the == false? It's not needed because either false or array is returned. A true test will return true if anything other than null or false is returned.
Try this
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false) {
if(input.value.length<len.min)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
const validateCname = value => value.length < 4 ? `success message` : `error message`
function validateCname(value1)
{
var k = value1;
if(k.length<4){
//Your code if length is less than 4
}else{
//Your code if length is more than 4
}
}
I want to check if the password length is at least 8 characters or not, when the user leaves the password field or press tab key.
How can i do this?
My code for password is shown below.
<input type="password" name="password" id="pass1" placeholder="password"/>
Use the jquery blur method for this.
$('#pass1').on('blur', function(){
if(this.value.length < 8){ // checks the password value length
alert('You have entered less than 8 characters for password');
$(this).focus(); // focuses the current field.
return false; // stops the execution.
}
});
Fiddle for Demo
You can use javascript onchange event as below
and script code callfunction() as
function callfunction()
{
var textBox = document.getElementById("pass1");
var textLength = textBox.value.length;
if(textBox.value=='' || textLength<=8)
{
alert('Please enter correct password');
}
}
try this:
$('#pass1').on('blur', function(){
if($(this).val().length > 8){
alert('safe!');
}
});
here is an example: http://jsfiddle.net/ACK2f/
Password validation can use several rules, I used a service but the code inside the function can be reusable:
_validatePassword = function (validateUserNameRules, Model)
{
//bolean parameter validateUserNameRules -> true/false
//this method recive a model like this:
//Model.userName -> string
//Model.password -> string
//Model.password2 -> String
var validationResult = {
ResultId: 1, //1 success
Message: "Password is correct."
};
if (validateUserNameRules && Model.userName == "") {
validationResult.ResultId = 2;
validationResult.Message = "Error: User name cannot be blank.";
return (validationResult);
}
var re = /^\w+$/;
if (validateUserNameRules && !re.test(Model.userName)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Username must contain only letters, numbers and underscores.";
return (validationResult);
}
if (Model.password != "" && Model.password == Model.password2) {
if (Model.password.length < 6) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must contain at least six characters.";
return (validationResult);
}
if (validateUserNameRules && Model.password == Model.userName) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must be different from the Account Name.";
return (validationResult);
}
re = /[0-9]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one number (0-9).";
return (validationResult);
}
re = /[a-z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one lowercase letter (a-z).";
return (validationResult);
}
re = /[A-Z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one uppercase letter (A-Z).";
return (validationResult);
}
} else {
validationResult.ResultId = 2;
validationResult.Message = "Error: Please check that you've entered and confirmed your password.";
return (validationResult);
}
return (validationResult); //success password validation!!
};
I have a form. I want to put validation so that It will check if user enters white spaces or not. If its white spaces then show error. How could I do this?
In case you want to detect if there is any white space all through the user's input string,
var str = $("input").val();
if( str.indexOf(" ") !== -1 )
{
alert("bad input");
}
Example: http://jsfiddle.net/pYquc/
Use jQuery.trim(str) which remove the whitespace or tabs and you can validate.
http://api.jquery.com/jQuery.trim/
Try this usong javascript:
var v = document.form.element.value;
var v1 = v.replace("","");
if( v1.length == 0){
alert("error");
}
OR you can use following functions:
// whitespace characters
var whitespace = " \t\n\r";
/****************************************************************/
// Check whether string s is empty.
function isEmpty(s)
{ return ((s == null) || (s.length == 0)) }
/****************************************************************/
function isWhitespace (s)
{
var i;
// Is s empty?
if (isEmpty(s)) return true;
// Search through string's characters one by one
// until we find a non-whitespace character.
// When we do, return false; if we don't, return true.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (whitespace.indexOf(c) == -1) return false;
}
// All characters are whitespace.
return true;
}
function doValidations(){
if(jQuery.trim( $(".className").val())==""){
alert("error message");
return false;
}else{
return true;
}
}
<input type="submit" onclick="return doValidations();">
I'm not sure if I'm misunderstanding how True/False works in Javascript or not.
In my Jquery script below I'm declaring 6 variables as false.
If the regex validation conditions are good, then I redeclare the variable(s) to true.
On the bottom is a simple alert() to tell me when all variables are true.
The validation conditions are working (removing/adding classes), but the alert does not show up. That's why I'm not sure if I'm messing up the true/false part or not.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
if(pswd.length < 6 ){
$('#length').removeClass('valid').addClass('invalid');
}else{
$('#length').removeClass('invalid').addClass('valid');
checkLength = true;
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
//validate no spaces
if(pswd.match(/\s/)){
$('#spaces').removeClass('valid').addClass('invalid');
}else{
$('#spaces').removeClass('invalid').addClass('valid');
checkSpace = true;
}
// here is where I'm concerned I'm wrong
if(checkLength == true && checkLetter == true && checkCaps == true && checkNum == true && checkSymbol == true && checkSpace == true){
alert("All good");
}
});
Would someone double check me?
At first, there is no need to write checkLength == true, checkLength is enough since they are all boolean variables.
Second, in some of your conditions you assign class invalid but set the var to true, while in others you do it vice versa. Every check... = true should be in the same branch with class = valid.
Also, personally, I would adapt the validity conditions, to have all positive events either in the if or in the else branch, but not mixed like you do at the moment.
Lastly, I always try to avoid duplicate code. There are a lot of places you could refactor, but you could start easy with setting the classes in a separate function.
See it working in this fiddle.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
// reverse the condition, to have the valid state in the if branch as well
if(pswd.length >= 6 ){
setValid('#length');
checkLength = true;
}else{
setInvalid('#length');
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
setValid('#letter');
checkLetter = true;
}else{
setInvalid('#letter');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
setValid('#capital');
checkCaps = true;
}else{
setInvalid('#capital');
}
//validate number
if(pswd.match(/\d/)){
setValid('#number');
checkNum = true;
}else{
setInvalid('#number');
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
setValid('#symbol');
checkSymbol = true;
}else{
setInvalid('#symbol');
}
//validate no spaces
if(!pswd.match(/\s/)){
setValid('#spaces');
checkSpace = true;
}else{
setInvalid('#spaces');
}
function setValid(e){$(e).removeClass('invalid').addClass('valid')}
function setInvalid(e){$(e).removeClass('valid').addClass('invalid')}
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace){
alert("All good");
}
console.log("keyup");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password1" type="text">
All of these have check* = true in the wrong place:
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
Insert the statements in the block following the if (where they are deemed valid) as opposed to in the else (where they are deemed invalid):
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
checkLetter = true;
}else{
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
checkCaps = true;
}else{
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
checkSymbol = true;
}else{
$('#symbol').removeClass('valid').addClass('invalid');
}
And, although there are better ways of writing validation, this is a similar, yet more concise version of your snippet:
$("#password1").keyup(function() {
var pswd = $(this).val();
var checkLength = pswd.length >= 6;
var checkLetter = /[A-Za-z]/.test(pswd);
var checkCaps = /[A-Z]/.test(pswd);
var checkNum = /\d/.test(pswd);
var checkSymbol = /[^A-Za-z0-9]/.test(pswd);
var checkSpace = !/\s/.test(pswd);
$("#length") .removeClass("valid invalid").addClass(checkLength ? "valid" : "invalid");
$("#letter") .removeClass("valid invalid").addClass(checkLetter ? "valid" : "invalid");
$("#capital").removeClass("valid invalid").addClass(checkCaps ? "valid" : "invalid");
$("#number") .removeClass("valid invalid").addClass(checkNum ? "valid" : "invalid");
$("#symbol") .removeClass("valid invalid").addClass(checkSymbol ? "valid" : "invalid");
$("#spaces") .removeClass("valid invalid").addClass(checkSpace ? "valid" : "invalid");
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace) {
alert("All good");
}
});
To me, it seems that your assignments are valid statements. Whether or not they are getting set the way you want is a different matter.
It is most likely that one of the flags is not being set the way you want it to be set. To check this, you could alert each of your flags (checkCaps, etc) to confirm that each value is set the way you want. If all of the true/false is correct, then the issue would be in your final if statement.
As many people have suggested, removing the == true is a good idea. Since Javascript is dynamically typed, there is a slight possibility that it is not treating your flags as a boolean, but as something else.
If removing the == true does not work, you could check different pairs of flags to see which one makes the entire statement false.