Form Password Validation without using regex [duplicate] - javascript

This question already has answers here:
Javascript regular expression password validation having special characters
(16 answers)
Closed 6 years ago.
Im trying to make a password validation without using regular expression so yeah only javascript no pattern or regex. The format must contain 1 uppercase letter,1 lowercase letter,1 number and 1 special character.So the format must be like this :
aaaa111 -> Invalid format
AaAa111 -> Invalid format
A#Ba213 -> Valid format
EDIT: im so sorry i dont know that regex include in javascript.. iam trying this validation but didnt work
var hasBigLetter = false;
var hasSmallLetter = false;
var hasNumber = false;
var hasSpecialCaseLetter = false;
for (var i = 0; i < pass.length; i++) {
var charCode = pass.charCodeAt(i);
if(charCode > 47 && charCode < 58)
hasNumber = true;
if(charCode > 64 && charCode < 91)
hasBigLetter = true;
if(charCode > 96 && charCode < 123)
hasSmallLetter = true;
if(charCode > 32 && charCode < 48)
hasSpecialCaseLetter = true;
}
if(pass == hasBigLetter && hasSmallLetter && hasNumber && hasSpecialCaseLetter)
{
alert("incorrect password pattern");
}
HTML:
<label>
Password :
<div>
<input type="password" placeholder="Input Password" id="pass" name="pass" >
</div>
</label>
<input type="button" value="Submit" id="submit" onClick="validate()">
</form>

As you now accepted to use RegEx, I adapted the solution based on this post https://stackoverflow.com/a/16707675/4339170:
function validate() {
var p = document.getElementById('pass').value
var errors = []
//if (p.length < 8) {
// errors.push("Your password must be at least 8 characters")
//}
if (p.search(/[a-z]/) < 0) {
errors.push("Your password must contain at least one lowercase letter.")
}
if (p.search(/[A-Z]/) < 0) {
errors.push("Your password must contain at least one uppercase letter.")
}
if (p.search(/[0-9]/) < 0) {
errors.push("Your password must contain at least one digit.")
}
if(p.search(/[\!\#\#\$\%\^\&\*\(\)\_\+\.\,\;\:\-]/) < 0) {
errors.push("Your password must contain at least one special character.")
}
if (errors.length > 0) {
document.getElementById("errors").innerHTML = errors.join("<br>")
return false;
}
return true;
}
<label>
Password :
<div>
<input type="password" placeholder="Input Password" id="pass" name="pass">
</div>
</label>
<input type="button" value="Submit" id="submit" onClick="validate()">
<div id="errors"></div>

Related

Allow only numbers and letters to input string

I'm trying to avoid input of any marks except numbers and letters with input string on my page.php:
<input type="text" id="input">
From this answer only allow English characters and numbers for text input <input type="text" id="input" class="clsAlphaNoOnly"> :
$(document).ready(function () {
$('.clsAlphaNoOnly').keypress(function (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
})
or this:
$(function(){
$("#input").keypress(function(event){
var ew = event.which;
if(ew == 32)
return true;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
return false;
});
});
in both cases string is clear, but I'm using two types of input with button click $("#btn").click(function() to process input and $(document).keypress(function(e) with hit on enter key on keyboard for same input. By some reason if I include this methods to avoid extra marks in string, pressing on enter key does not allows to input inserted value.
This way works fine:
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
but I want avoid extra code with html in page.php. I'm trying to figure out, what causes blocking of entering for inserted value with given methods
Would tell you may miss event parameter ?
Without jQuery works like this for me in 3 browsers:
function clsAlphaNoOnly (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
function clsAlphaNoOnly2 () { // Accept only alpha numerics, no special characters
return clsAlphaNoOnly (this.event); // window.event
}
<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">
One way of validation is using pattern attribute on input element
MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression
In your case:
<input type="text" pattern="[a-zA-Z0-9]*">
If you really do not want to use the Regex method as the comments bellow advice you, then you can use this simple code :
document.querySelector("input#testInput").addEventListener("input", function(){
const allowedCharacters="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNzáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ "; // You can add any other character in the same way
this.value = this.value.split('').filter(char => allowedCharacters.includes(char)).join('')
});
<input type="text" id="testInput">
Instead of javascript you could use a pattern along with required. pattern will allow you to specify a required pattern for the input, and required will make the input required. Both must evaluate to true in order for the form to submit.
<form>
<input type="text" id="input" pattern="[a-zA-Z0-9]+" required>
<input type="submit">
</form>
HTML Input Way :
1- Simple HTML5 Input
<input type="text" pattern="[a-zA-Z0-9]*">
2- Inline Function
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
Jquery Way :
$('#ID').on('keypress', function (e) { var code = ('charCode' in e) ? e.charCode : e.keyCode; if (!(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) {e.preventDefault();}});
Javascript Function :
function allowAlphaNumericSpace(e) {
var code = ('charCode' in e) ? e.charCode : e.keyCode;
if ( !(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) { e.preventDefault();}};
<input type="text" onkeypress="allowAlphaNumeric(event)" />

Validation input field Fullname(Firstname,Lastname) - JavaScript

Need validation for full name(first name/last name - 1 input field). I'm new in this sphere and can't formulate the right syntax maybe will work with a regular expression too
<form name="myForm" action="#" id="form" onsubmit="return validateForm()" method="POST">
<div class="field"><span class="input"><i class="fas fa-user-alt"></i>
<input type="text" id="name" name="Fullname" placeholder="Full Name" >
</span>
function validateForm() {
var name= document.getElementById('name').value;
var x = name.indexOf(" ");
var fname = name.substring(0, x);
var lname = name.substring(x).trim();
if ( 17 < fname.value.length < 5 || 4 > lname.value.length > 17 || x.value.length != 1) {
alert("try again")
return false;
}
alert("OK")
return true;
}
The field (1 field) should contain 2 words which should be from 3 to 20 symbols.
EDIT:It seems work..finally!
function input (name) {
let fullNameArr = name.split('')
const space = ' '
let firstName = ''
if (fullNameArr.includes(space)) {
for (let i = 0; i < fullNameArr.length; i++) {
if (!firstName.includes(space)) {
firstName += fullNameArr[i]
}
}
}
firstName = fullNameArr.splice(0, firstName.length)
const lastName = fullNameArr
if (firstName.length > 3 && firstName.length <= 21 && lastName.length >= 3 && lastName.length <= 20 && lastName.includes(space) === false) {
console.log(firstName)
console.log(lastName)
} else {
console.log('Invalid Name')
return false
}
}
input('Todor Markov')
Your model makes several assumptions about names. Having first name and last name as separate input boxes is typically done to remove this barrier.
From a UX standpoint, if you were not going to have separate fields, you'd need some validation with a tooltip that checked if the user has more than one space that alerts them they must type FirstName LastName.
From a regex validation view, here's a catch all to ensure it's valid.
/^[a-z ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.")
No numbers, but allow letters and the special characters ,.'-.

Prevent special chars in text area

I need to prevent special characters to being inserted in the text area. It should work across all browsers.
I've tried to do it but it won't check "~" and "ã" and "á". In this case "ã" get same code as "a".
$('#sms_text').keydown(function(e) {if((e.keyCode>64 && e.keyCode<91) || (e.keyCode>96 && e.keyCode<123) || e.keyCode==8)
{}
else{e.preventDefault();}});
$('#sms_text').keyup(function(e){if((e.keyCode>64 && e.keyCode<91) || (e.keyCode>96 && e.keyCode<123) || e.keyCode==8)
{}
else{e.preventDefault();}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class="form-group" style="width:40%">
<label for="exampleInputEmail1">Email address</label>
<textarea class="form-control" id="sms_text"></textarea>
<div class="text-right">
<h6 class="badge badge-dark"><span id="count_message">0</span>/50</h6>
</div>
</div>
I should expect prevent in that special cases.
Take a look to the jQuery alphanumeric plugin! enter link description here
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
let textAreaContainer = $('#sms_text');
textAreaContainer.keyup(function(e){
if (e != "") {
if ( /[^\w\d]/.test(e)) {
alert("Please enter only letter and numeric characters");
return (false);
} else { e.preventDefault()}
}
})
this expression match
Match a single character not present in the list below [^\w\d]
\w matches any word character (equal to [a-zA-Z0-9_])
\d matches a digit (equal to [0-9])
or may be a solution with ur approach with this condition on the if
((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57) || k == 190 || k == 188)

Mask input on html does not work

I'm trying to create a mask to my input, but one strange error happens. I have to enter 11 numbers, and my mask have to make it like this: ###.###.###-##. But when I enter the sixth digit my current input become blank. I have no idea what is the problem.
This is my script:
function mascararCpf(){
var cpf = document.getElementById("idCpf");
if((cpf.value.length == 3) || (cpf.value.length == 6)){
cpf.value += ".";
return;
}
if(cpf.value.length == 9){
cpf.value += "-";
return;
}
}
And this is my input:
<label> CPF: <input type="number" autocomplete="on" name="cpf" id="idCpf" placeholder="Seu CPF" required onblur="validarCpf()" onkeypress="mascararCpf()"></label>
Try with
<input type="text" ...
problem with the input type number
DEMO
If you want to open Numeric keypad on focus, I would suggest you to use
<input type="tel" ...
Another DEMO
That's because you need to count dots . as part of the length. "123.456" is SEVEN characters long.
It is a common practice to put several input fields (in your case 4 fields) and to go from one field to the other when the length of the field (3) has been reached.
As noted before the input type should be text. Furthermore, you should consider that the length of the input value increases after appending a '.' or '-'.
Your html is not valid. The <label>-tag should be closed before opening <input>.
It's better not to use inline handlers. You can assign your hander in the script. Using type="text" the input value can also be non numeric. If you want the mask-method to check that you should add checking of the inputted value. A tentative method could be:
// bind handler to the input field
document.querySelector('#idCpf').onkeypress = mascararCpf;
// the handler method, including a numeric-check for the entered value
function mascararCpf(e){
var len = String(this.value).length;
this.value += len === 3 || len === 7 ? '.' : len === 11 ? '-' : '';
return isNaN(+String.fromCharCode(e.keyCode)) ? false : true;
}
Here's a jsFiddle demonstrating it all
I had a similar need, so I developed the following code. Not 100% yet, but it works.
function editMask(mask,element,e) {
if (e.keyCode >= 48 & e.keyCode <= 57 | e.keyCode >= 96 & e.keyCode <= 105 | e.keyCode == 46 | e.keyCode == 8) {
var v = element.value;
var N = v.replace(/\D/g,'');
var L = N.length;
var r = '';
var resp = '';
for (i=0;i<mask.length;i++) {
if (mask[i] == '_') {
if (N.length > 0) {
r = N[0];
N = N.substring(1,N.length);
} else {
r = '_';
}
} else {
r = mask[i];
if (N.length > 0) {
L++;
}
}
resp = resp+r;
}
element.value = resp;
element.setSelectionRange(L,L);
}
}
It's called in the onkeyup event of the input:
<input type='text' size=20 id='insPFis_CPF' value='$CPF' onkeyup='javascript:editMask(\"___.___.___-__\",this,event)'>
You may want to change the mask format for CNPJ, phone numbers, etc. I hope it helps.

Preventing user to enter more numbers after 2 digits before decimal point

I'm having a problem with letting users enter numeric values in my textboxes which have the same class.
What I Want:
Allow users to enter only 2 numbers before the decimal points and another 2 after it; otherwise all keys are log except arrows keys, backspace, and delete key
Current Issue
Users can only enter 2 numbers; however, after he/she adds a decimal points, they can add more numbers before it
Currently, users can only enter 5 digits--2 before the decimal point, and another 2 after the decimal points. When they delete one digit after the decimal point, they can still add more number to digit before that decimal point.
My HTML:
<form method="post">
<div class="row">
<label>Val 1</label>
<input type="text" class="validate" name="val1" maxlength="5" />
</div>
<div class="row">
<label>Val 2</label>
<input type="text" class="validate" name="val2" maxlength="5" />
</div>
<div class="row">
<label>Val 3</label>
<input type="text" class="validate" name="val3" maxlength="5" />
</div>
<div class="row">
<button type="submit">Send</button>
</div>
</form>
My JS:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.validate').keypress( function( event ) {
var v = parseFloat($(this).val() + String.fromCharCode(event.which));
textValue = parseFloat(v).toString();
var newVal = parseInt( textValue.substr(0, textValue.indexOf(".")) );
console.log(newVal);
if(textValue.length < 6){
if(!parseFloat(v).between(0,99.99,true)) {
v = this.value.substring(0, 2);
$(this).val(v);
return false;
}
return true;
}
});
Here is the link to my fiddel DEMO
Try this :
<input type="text" class="validate" name="val1" maxlength="5" onkeypress="return CheckDecimalValues(event)" />
function CheckDecimalValues(evt) {
var keyCode = evt.keyCode ? evt.keyCode : ((evt.charCode) ? evt.charCode : evt.which);
// 8 Backspace
// 9 Tab key
// 46 Delete
// 35 End Key
// 36 Home Key
// 37 Left arrow Move
// 39 Right arrow Move
if (!(keyCode >= 48 && keyCode <= 57)) {
if (!(keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 39 || keyCode == 46)) {
return false;
}
else {
return true;
}
}
var velement = evt.target || evt.srcElement
var fstpart_val = velement.value;
var fstpart = velement.value.length;
if (fstpart .length == 2) return false;
var parts = velement.value.split('.');
if (parts[0].length >= 14) return false;
if (parts.length == 2 && parts[1].length >= 2) return false;
}
Why don't you use a regex to validate your requirement?
A simple regex like so:
[0-9]{1}[0-9]{1}[\.]{1}[0-9]{1}[0-9]{1}
can be used to validate the input without worrying about the key strokes. Just add an onblur event on your textbox to validate this.
EDIT:
I have added this Fiddle
Check it out.

Categories

Resources