Javascript Validate only .com websites how to validate? - javascript

For Example:-
google.com
msn.com
other than .com is not allowed how to wrote the regex?

If you only need to ensure that the string ends with ".com" this regex should work :
^.*\.com$

This is what foundation abide library states regex for validating a domain:
/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/
just modified it to only accept .com:
/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+com$/

var site_path=window.location.origin;
var splitted_path=site_path.split(".");
if(splitted_path[splitted_path.length-1]=="com")
{
// DO IF .COM.
}
else
{
// DO IF ANOTHER.
}

Just split them when . comes and check if the current element is equals to .com for every element Your question answer is the below code:
const validateCom = (str) =>{
let total = ""
let errorMessage = ""
let error = false;
if(str != null && str != ""){
let array = str.split(".")
array.forEach((element=>{
if(element === "com"){
total = "Yes, its .com"
// Type your code if its .com here
}else{
total = "No, its not .com"
// Type your code if its not .com here
}
}))
}else{
error = true;
errorMessage = "Please fill the str perimeter"
return errorMessage
}
return total;
}
// Calling Function
console.log(validateCom("demo.com"));

Related

Why this regular expression return false?

i have poor eng, Sorry for that.
i'll do my best for my situation.
i've tried to make SignUpForm using regular expression
The issue is that when i handle if statement using the regular expression
result is true at first, but after that, become false. i guess
below is my code(javascript)
$(document).ready(function () {
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/g; // more than 6 words
var pwCheck = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // more than 8 words including at least one number
var emCheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; // valid email check
var signupConfirm = $('#signupConfirm'),
id = $('#id'),
pw = $('#pw'),
repw = $('#repw'),
email =$('#email');
signupConfirm.click(function () {
if(id.val() === '' || pw.val() === '' || email.val() === ''){
$('#signupForm').html('Fill the all blanks');
return false;
} else {
if (idCheck.test(id.val()) !== true) {
$('#signupForm').html('ID has to be more than 6 words');
id.focus();
return false;
} else if (pwCheck.test(pw.val()) !== true) {
$('#signupForm').html('The passwords has to be more than 8 words including at least one number');
pw.focus();
return false;
} else if (repw !== pw) {
$('#signupForm').html('The passwords are not the same.');
pw.empty();
repw.empty();
pw.focus();
return false;
}
if (emCheck.test(email.val()) !== true) {
$('#signupForm').html('Fill a valid email');
email.focus();
return false;
}
}
})
});
after id fill with 6 words in id input, focus has been moved to the password input because the condition is met.
but after i click register button again, focus move back ID input even though ID input fill with 6 words
i've already change regular expression several times. but still like this.
are there Any tips i can solve this issue?
I hope someone could help me.
Thank you. Have a great day
Do not use the global flag on your regexes. Your code should be:
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/;
When you match with the /g flag, your regex will save the state between calls, hence all subsequent matches will also include the previous inputs.
use
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/
removing the g flag
and modify the line
else if (repw.val() !== pw.val()) {

Regex modification needed to enforce atleast one special symbol character

I'm using the following regex for a password field :
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*()_+]{7,63}$/
I'd like to enhance it to force atleast one number , one alphabet and one special symbol.
I'm using the following JavaScript code to validate the same :
function validatePassword()
{
var password = document.getElementById('password').value;
var userID = document.getElementById('user_ID').value;
var regexPattern = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*()_+]{7,63}$/ ;
if(regexPattern.test(password))
{
if(userID === password )
{
$('#status').text( 'User id is same as password . Please choose a more secure password');
return false;
}
else if(password === reverse(userID))
{
$('#status').text( 'Password is reverse of user id . Please choose a more secure password');
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
How do I do it ?
Thanks.
Instead of using regex you can check like this also.
Just replace
if(regexPattern.test(password))
with
if(regexPattern.test(password) && /[a-zA-Z]/.test(password) && /[0-9]/.test(password) && /[\!\#\#\$\%\^\&\*\(\)\_\+]/.test(password) )
Check string if it is valid password, contain alphabet, number and special character ( if you want more add in range ).

Javascript function not working after switching to whirlpool

I've been following a guide to make a secure login page ( given I'm a newbie to PHP, and I'm trying to learn it ); they use javascript as a processor after you've clicked "submit" on the register page, and the login page. However, the function seems to be broken. I've edited it, so that the salt is converted to whirlpool, instead of sha512.
Here's the function ( also, the link to the guide: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL )
Function:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = whirlpool(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
function regformhash(form, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
form.username.focus();
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
form.password.focus();
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
form.password.focus();
return false;
}
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = whirlpool(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
conf.value = "";
// Finally submit the form.
form.submit();
return true;
}

Javascript Email Validation Specific Domain

I'm trying to get someone to use a specific email domain of #mail.fhsu.edu. Here is my Validation code.
function validateFHSUEmail(inputField, helpText) {
if (inputField.value.length == 0) {
if (helpText != null) {
helpText.innerHTML = "Please Enter a Value";
}
return false;
} else {
var reg = /^[a-z.]+#mail.fhsu.edu$/;
if (!reg.test(inputField)) {
if (helpText != null) {
helpText.innerHTML = "Please Enter FHSU Email";
}
Am I calling it wrong or what because no matter what it returns false.
You're testing the variable "inputField", which apparently is a reference to a DOM element. You want inputField.value in the test.
edit Note the comment wherein it's pointed out that your regex should use \. for the periods in the domain name.
If you want valid email and specific domain try this regex:
/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#domain.com$/

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.
Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}
try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...
I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}
If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.
I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}
Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Categories

Resources