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 ,.'-.
Related
I have this script and want to implement 12 character limit for each name like first name, last name and middle name can not have more than 12 characters each.
var name = prompt("Please enter (Last name, First name, Middle initial)");
function fullName(alf) {
var validate = alf.match(/^[a-zA-Z', ]+$/);
if (validate == name)
return true;
else
return false;
}
var tst = fullName(name);
if (tst)
document.write("Valid Name");
else
document.write("Invalid Name");
It's fairly simple. Just check the prompt input length as in this snippet. (However if you use input field instead of a prompt you can limit its length by defining "maxlength" e.g. <input type="text" name="yourname" maxlength="10">)
var name = prompt("Please enter (Last name, First name, Middle initial)");
function fullName(alf) {
var validate = alf.match(/^[a-zA-Z', ]+$/);
if (validate == name)
return true;
else
return false;
}
var len = name.length;
var tst = fullName(name);
if (tst && len <= 39) // len 12 * 3 for each value + 3 for spaces/commas separating names.
document.write("Valid Name");
else
document.write("Invalid Name");
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>
Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/
The JavaScript below just checks if there are 4 digits in a field or not and then warns if there isn't.
But for some reason, if I enter four zeros (0000) it takes that as an empty field and throws the warning.
Any idea how to fix this...?? I am no programmer but have put this code together after weeks of trial-and-error.
function validate(){
// if ( (!isNaN($("#couponstart1").val())) || (!isNaN($("#couponstart2").val())) || (!isNaN($("#couponend1").val())) || (!isNaN($("#couponend2").val())) ) {
var all_ok = true;
var err_msg = "";
var fld = "";
if ( $("#couponstart1").val() == '' || $("#couponstart2").val() == '' || $("#couponend1").val() == '' || $("#couponend2").val() == '' ) {
all_ok = false;
err_msg += "\n - Card Numbers cannot be blank";
fld='couponstart1';
}else{
if ( isNaN($("#couponstart1").val()) || isNaN($("#couponstart2").val()) || isNaN($("#couponend1").val()) || isNaN($("#couponend2").val()) ) {
all_ok = false;
err_msg += "\n - Card Number has to be numeric";
fld='couponstart1';
}else{
if ( $("#couponstart1").val() < 1 || $("#couponstart2").val() < 1 || $("#couponend1").val() < 1 || $("#couponend2").val() < 1 ) {
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}else if ($("#couponstart1").val().length != 4 || $("#couponstart2").val().length != 4 || $("#couponend1").val().length != 4 || $("#couponend2").val().length < 4){
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}
}
}
if (all_ok == false){
alert("The following errors have taken place" + err_msg);
setFocus(fld);
}
return all_ok;
}
It's sad that computers do what we ask, not what we want.
If your input is filled with 0000, and you compare < it with the number 1: ($("#couponstart1").val() < 1, javascript will try to parse the value 0000 to the operand type which accounts to 0. So it is right to say that 0 is lower than 1and you'll get your error message Card number are not correct.
Let's try a different approach:
<!-- html -->
<form>
<p>
<label for="couponstart1">Coupon Start Part 1</label>
<input type="text" maxlength="4" id="couponstart1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start Part 2</label>
<input type="text" maxlength="4" id="couponstart2" class="validateme" />
</p>
<p>
<label for="couponend1">Coupon End Part 1</label>
<input type="text" maxlength="4" id="couponend1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start End 2</label>
<input type="text" maxlength="4" id="couponend2" class="validateme" />
</p>
<button type="button" id="testit">Test</button>
</form>
and:
/* javascript/jQuery */
$(document).ready(function(){
$("#testit").click(function(){
var rgx = /\d{4}/;
var allgood = true;
$("input.validateme").each(function(){
if( ! rgx.test( $(this).val() ) ){
alert("Card number for " + ($('label[for="' + $(this).attr("id") + '"]').text()) + " is not correct!\nPlease use 4 digits all numbers!");
$(this).select();
allgood = false;
return false;
}
});
if(allgood) alert("All good!");
});
});
Basically we have a form with 4 inputs with "validateme" class.
With jQuery we loop over the inputs that have this class an run it against the regex /\d{4}/ which basically will test for a number(\d) exactly 4 digits long ({4}) meaning from 0000 to 9999. Note that we use the label of the input to identify which field is not right.
Otherwise, all good.
You can fiddle with this code here: http://jsfiddle.net/L8dcgcrs/1/
Assuming the four digits correspond to $("#couponstart1").val(), $("#couponstart2").val(), $("#couponend1").val(), $("#couponend2").val() then the problem is that in JavaScript there are two types of comparison operators.
In your first if statement you choose to evaluate if $("#coupontstart1").val() == '' || ...). In this case you are using an equality operator which converts the operands if they are not the same type. So using this operator 0 == '' returns true. Instead you could use the strict equality operator === in the following manner:
if ( $("#couponstart1").val() === '' || ...)
In which case 0 === '' would return false. This most likely will help you in the first if statement you write as entering 0000 would make all the conditions false and you would proceed to the else block.
Hope this helps!
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.