How to check regex match in javascript - javascript

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

Related

Why is my email validation not returning an error message I did set?

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

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

localStorage Overwritten/ and innerHTML fail

On the 14th and 28th line, it's not changing the text of the label tag and on the recorForm or loginSetup, data is overwritten. I tried loop with .key, but it outputed the wrong stored results and I'm not sure what I did wrong. so I'm leaving it at this. What I want to know is why the innHTML of the label won't change.(I assume it's due to loading)
window.onload = alert('Window Loaded');
function recordForm() {
var userMail = document.getElementById('email').value;
var userPass = document.getElementById('password').value;
var confirm = document.getElementById('confirmation').value;
var text = document.getElemetsByClassName('errorText');
//Check that the email is not taken and confirm validation
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail.value);
localStorage.setItem('passwordz', userPass.value);
} else {
text.innerHTML = 'Password does not match!'; //line 14
}
}
function loginSetup() {
var mail = localStorage.getItem('emailz');
var pass = localStorage.getItem('passwordz');
var mailInput = document.getElementById('logEmail').value;
var passInput = document.getElementById('logPassword').value;
if ((mailInput === mail) && (passInput === pass)) {
alert(mail);
alert(pass);
} else {
text.innerHTML = 'Invalid login'; //line 28
alert('no dice');
alert(mail);
alert(pass);
}
}
You should try to store userMail.value and userPass.value. Both yet are already the values:
var userMail = document.getElementById('email').value; //Those are values already
var userPass = document.getElementById('password').value; //Those are values already
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail); //Remove the .value
localStorage.setItem('passwordz', userPass); //Remove the .value
}
Also getElementsByClassName returns a collection, thus you want to select the first item of it (assumably):
var text = document.getElemetsByClassName('errorText'); //Misstyped and no index.. wont work
var text = document.getElementsByClassName('errorText')[0]; //Should work
var text = document.querySelector('.errorText'); //Would prefer that one
At last in the function loginSetup() you have to redefine text:
var text = document.querySelector('.errorText');

Loading form input fields into a javascript array and then validating

I seem to be really stuck on something. I have a function to check if all the form input fields are equal to null or "" which is all fine but wanted to see if there is another way of doing it by loading all the fields into a javascript array and then doing a for loop along with an if statement to check if any of the fields are empty, unfortunately I can't seem to get this to work and wondering if I've simply just missed something some where. Here is my code:
function checkempty()
{
fname = document.getElementById("firstname").value;
lname = document.getElementById("lastname").value;
fage = document.getElementById("age").value;
addressl1 = document.getElementById("addressline1").value;
addressl2 = document.getElementById("addressline2").value;
ftown = document.getElementById("town").value;
fcounty = document.getElementById("county").value;
fpcode1 = document.getElementById("pcode1").value;
fpcode2 = document.getElementById("pcode2").value;
ftelephone = document.getElementById("telephone").value;
fcomment = document.getElementById("comment").value;
var myArray = [];
myArray[0] = fname;
myArray[1] = lname;
myArray[2] = fage;
myArray[3] = addressl1;
myArray[4] = addressl2;
myArray[5] = ftown;
myArray[6] = fcounty;
myArray[7] = fpcode1;
myArray[8] = fpcode2;
myArray[9] = ftelephone;
myArray[10] = fcomment;
for(i=0;i<myArray.length;i++)
{
if(!myArray[0])
{
return true;
}
}
return false;
}
I then use another function:
function checkform()
{
if(checkempty)
{
display_errormessage("One or more fields empty!");
}
else
{
alert("Thanks for you input!");
}
}
The display_errormessage() function is just one that puts an error message into a div at the top of the form to display an error message if the form is incomplete.
Can anyone see where i've gone wrong?
Thanks in advance for any help!
Dave.
First, function checkform is not called. The if (checkform) should be if (checkform()) or you will test only test the availability of the function, not the result.
Then the if (!myArray[0]) should be if (!myArray[i]) to not only test the firstname
Or better, if (myArray[i].length==0) to be sure to explicitly test for empty string and not just doing an implicit boolean conversion (javascript evaluate 0=="" as true)
if(!myArray[0]) should be if(!myArray[i]), but a larger point is you're only validating that the value isn't falsey (null, '', 0, false, etc.), not that it's appropriate for the task.
Guess you won't need this function as you've already fixed yours, but I'll leave it here as it may be helpful in the future. JSFiddle
function checkform()
{
arr1 = document.getElementsByTagName('input');
arr1 = Array.prototype.slice.call(arr1);
arr2 = document.getElementsByTagName('textarea');
arr2 = Array.prototype.slice.call(arr2);
arrs = arr1.concat(arr2);
for(i=0;i<arrs.length;i++)
{
if (arrs[i].type == "text" || arrs[i].type == "textarea")
{
if (arrs[i].value == '')
{
alert("Fill all fields before submitting!");
return false;
}
}
}
alert("Thanks for your input!");
return true;
}
According that your input fields are in the form named form:
var allTrue = [].every.call( document.forms.form.elements, function( el ) {
return !!el.value;
} );
if ( allTrue ) {
alert( "Thanks for your input!" );
}
else {
alert( "Some fields are missing!" );
}

how to validate space in htmleditor using javascript

function CheckDateEmpty(oSrc,args)
{
var editor = $find("<%=editorContent.ClientID%>");
var value = editor.get_content();
if (value == "")
{
args.IsValid = false;
return;
}
else
{
editor.set_content(value);
args.IsValid = true;
return;
}
}
the above function check perfectly weather the html editor is empty or not....but if i'll
enter space in my editor ...it consider it as a value ...i want it validate for the space...
Using a regex, check if all characters are whitespaces:
if (value.match(/^\s*$/))

Categories

Resources