Add JavaScript min length validation to text field? - javascript

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

Related

How to validate a url and a text?

In one of my textbox i need to enter only multiple url or multiple text at a time,not both.
So while i use the regular expression given below the domain name "google.com" will satisfy the condition of text.But i need to return false for this type of entry.Can anyone please suggest an idea?
jQuery.validator.addMethod("newway", function(value, element) {
var testarray = ['.....'];
var url_count = 0;
var text_count = 0;
for(var k in testarray){
if(/^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i.test(testarray[k]))
{
console.log("url");
url_count++;
}
else{
if(/^[a-zA-Z+,:;%()]+$/.test(testarray[k])){
console.log("text");
text_count++;
}
}
}
if((url_count==0 && text_count > 0) || (url_count >0 && text_count == 0)){
if((url_count==testarray.length) || (text_count==testarray.length)){
return true
}
else{
return false
}
}else{
return false
}
}, "Please enter url or text");

Regular Expressions for phone numbers and mobiles doesn'nt work correctly

I have a function for validating telephone and mobile numbers. Here is part of my function:
function IsPhone(){
var mob = /09[123]\d{8}$/;
var phn = /0\d{10}$/;
for (var i = 0; i < edit_rows.length; i++) {
if (edit_types[i] == 5) {
var phon_val = document.getElementById('phone1').value;
if (phon_val != "") {
if (phon_val.match(mob))
return true;
else if (phon_val.match(phn)) {
if ((phon_val).length == 11)
return true;
}
else {
msg_req += "Invalid format";
return false;
}
}
}
}
return true;
}
But it accepts all of these:
009153842716
09153842716
001234567890
01234567890
what can I do?
I think adding a ^ at the beginning of your expression would fix it. Your current query would match strings like 'thisisaninvalidvalue09153842716'. Adding the ^ makes sure you don't start with invalid input.

How to check textfield for whitespaces in jquery

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();">

javascript If Variable(s) is True

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.

regular expressions javascript validation

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)">

Categories