I am trying to come up with one function that can handle if statements in my code to avoid repetition of the same. For example in the code below
// email
App.Cmp.form.ValidateEmail = function(email) {
var MyEmailId = document.getElementById(email);
var format = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (!MyEmailId.value.match(format)) {
this.displayWarning(email, MyEmailId.parentNode.id, "Invalid email!");
} else {
removeWarning(email, MyEmailId.parentNode.id);
}
}
// password
App.Cmp.form.ValidatePassword = function(password) {
var MyPasswordId = document.getElementById(password);
var format = /(?=^.{8,}$)(?=.*\d)(?=.*[!##$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[A-Z]).*$/;
if (!MyPasswordId.value.match(format)) {
this
.displayWarning(
password,
MyPasswordId.parentNode.id,
"The password must have uppercase, lowercase, numeric and special characters and at least 8 characters long");
} else {
this.removeWarning(password, MyPasswordId.parentNode.id);
}
}
Related
When you input wrong password, incorrect alert show, but second time when you do it, it just let you on site.
var password = "Password123";
var pass = window.prompt("Enter password: ");
if (pass == sifra) {
alert("Correct");
} else {
var pass = window.prompt("Incorrect password: ");
}
You cause your code has no checks after the second prompt. In this scenario, You should write your code in a kind of recursion way. When the password check fails, It should begin the same process again and again until it passes.
// fn: verify the password
function verifyPassword(pass) {
if (pass === "sifra") {
alert("Correct");
} else {
// prompt the password again if it's incorrect
promptPassword("Incorrect password: ");
}
}
// fn: promoting the password
function promptPassword(msg = "Enter password:") {
var pass = window.prompt(`${msg} `);
// verify the password
verifyPassword(pass);
}
promptPassword();
This is happening because second time its just taking input but not validating password if you want to validate password untill its correct you can try this just add a loop
var pass = window.prompt("Enter password: ");
while (pass !== sifra) {
pass = window.prompt("incorrenct password try again: ");
}
// reaches here only when password is corrent
I made an email validation through Javascript. I know we can do validation through HTML, but I need to use Javascript. There are two methods that I used in this problem. First is conditioning, and second is regular expression matching. If an input email is wrong, then an error message will appear beside it, and if there's no error the form will direct to a PHP page. In my case, I input an email that I expect to get an error from, but it directs to the PHP page immediately, which is wrong.
What I want is there should be no '.' and '#' in the first and last index of the email
There should be an # and . as per the usual email structure
There should only be 1 # character
All characters are included.
Here is my javascript code after the html one,
const name = document.getElementById('name')
const lname = document.getElementById('lname')
const co = document.getElementById('co')
const email = document.getElementById('email')
const form = document.getElementById('form')
const error1 = document.getElementById('error1')
const error2 = document.getElementById('error2')
const error3 = document.getElementById('error3')
const error4 = document.getElementById('error4')
form.addEventListener('submit', (e) => {
let messages = []
var re =/^[A-Za-z]+$/;
if(!name.value.match(re)){
messages.push('error')
var err1="Contains number";
}
else{
err1="";
}
if(!lname.value.match(re)){
messages.push('error')
var err2="Contains number";
}
else{
err2="";
}
var t=co.value;
//we have a problem in contact number
if(t[4]!='-'||t[8]!='-'||t[0]!=0||t[1]!=9||t.length!=13){
messages.push('error')
var err3="Must follow the format";
}
else{
err3="";
}
var m=email.value;
var r=email.value.length;
var atposition=email.indexOf("#");
var dotposition=email.lastIndexOf(".");
var i, count, dot1;
for(i=0; i<r; i++){
if(m[i]=='#'){
count++;
}
if(m[i]=='.'){
dot1++;
}
}
if(atposition<1||atposition==m[r-1]||count>1||dotposition==m[r-1]||m[0]=='.'||dot1==0||count==0){
messages.push('error')
err4.push('Must follow email format')
}
if (messages.length > 0) {
e.preventDefault()
error1.innerText = err1
error2.innerText = err2
error3.innerText = err3
error4.innerText = err4
}
})
Here is my method on regular expression matching:
var re=/^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/
if(!email.value.match(re)){
messages.push('error')
err4.push('Must follow email format')
}
try this one.
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]
{2,4})+$/;
var email = $('#email').val();
if(!mailformat.test(email_value)){
e.preventDefault();
$('#error-email-txt').html('Enter valid email address');
$('#error-email').css("display",'block');
}
Multiple email validation regex with semicolon in Javascript
It can allow mulptiple emails and can allow the semicolon after email id. If only one email id provided then it can allow with or without semicolon.
I tried below code:
<script type = "text/javascript" >
function myFunction() {
var email = document.getElementById("email").value;
var reg = /^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+)+([;]([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+))*$/;
if (reg.test(email) == false) {
alert("Entered email id is not valid")
return false;
} else {
alert("Entered email id is valid")
return true;
}
}
</script>
Try this approach.
It splits email list into individual addresses and loops over all of them. Also, it uses much simplified regex to check email validity.
Also, checking for validity of one email on the list should be more robust, this is only an example.
var email = document.getElementById("email").value;
console.log("Are emails valid: " + checkEmailValidity(email));
function checkEmailValidity(emailList) {
var reg = /^.+?#.+?\.\w{2,}$/i;
var emailArr;
if (emailList.indexOf(";") < emailList.indexOf("#")) {
//assume only one email address on the list
emailArr = [emailList];
} else {
emailArr = emailList.split(";")
}
var isValid = true;
emailArr.forEach(function(addr) {
if (reg.test(addr) === false) {
console.log("One of the emails is not valid: " + addr);
isValid = false;
}
})
return isValid;
}
I am having trouble with regex checking in javascript. I want when the user inputs in something to the text field my function should alert 'matched' or 'no match' according the regex in my code below. Please help
function chech_password() {
var str = document.getElementById("pass").value;
var patt = new RegExp("^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$");
var ress = patt.test(str);
if (ress != true) {
//$('#error_pass').html("wrong pasmatch");
//$('#error_pass').show();
//error_pass = true;
alert("no match");
} else {
//$('#error_pass').hide();
alert("match");
}
}
function ClientContactCheck(){
var clientcontact = $("#client_contact_id").val();
if(clientcontact.length != ""){
if(!isNaN(clientcontact)){
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
}
}else{
$("#client_contact_id").css('border-color', "red");
}
return false;
}
i am using this function to validation phone number , my intention is simple just not be empty and must be number.
but if put !isNaN and my input was 123-456-789 , it wont valid cause the - was not a number, how to i make my function bypass the - ?
so if the input value had - it will pass thought.
thank
You can use :
str.replace("-", "");
and then check your input if it is a number only.
Edit:
var res = str.replace(/\-/g,'');
You can check it with a regular expression:
var clientcontact = $("#client_contact_id").val();
if (/^[0-9\-]+$/.test(clientcontact)) {
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
} else {
$("#client_contact_id").css('border-color', "red");
return false;
}
This will allow '-', '--', '---' too. If that is not desired, you can do one more check: ... && !/^-*$/.test(clientcontact)
You can do something like this to validate the phone number.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
More at http://www.w3resource.com/javascript/form/phone-no-validation.php