how to check inserted regex pattern is valid or not - javascript

Hi guys I have to create a demo project, to check if inserted regex pattern is valid or not.
I have one text box.
With help of this text-box, I am entering the regex for date, email, time, etc.
But I don't know how can I do this type of validation check.
Help me out with this.
This is my fiddle: http://jsfiddle.net/ygfQ8/9/
It's not perfect, but just a view of how I am checking the pattern using jquery.
$('input').on('blur',function(){
var str = $('input').val();
var first = '(';
var last = ')';
var get_first = str.charAt( str.length1 );
var get_last = str.charAt( str.length -1 );
if(first==get_first && last==get_last)
{
alert('patter is valid');
}
else
{
alert('pattern is invalid');
}
});
and html textbox is <input type='text'>
This is php working demo:
<?php
//this variable containg any string .... doesnt matter wat ?
$subject = 'This is some text I am searching in'; //simple testing string variable
$pattern = '(fdsfdsfdsfdsfsd'; // user inputed string
if(#preg_match($pattern, $subject) === false)
echo "YOU have entered wrong regex pattern";
else
echo "Great work ";
?>

This could suit your needs:
function isPatternValid(pattern) {
try {
"".match(new RegExp(pattern));
return true;
} catch (err) {
return false;
}
}
Calling with:
$('#input').blur(function() {
alert(isPatternValid(this.value));
});

Related

CSRF protections cause "Invalid or Unexpected Token" error

I am trying to integrate CSRF protection on my forms, and I have started with my registration form that started out working before the CSRF tokens were added, but now just produce a "Invalid or Unexpected Token" error. Here is my current form:
<form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
First Name: <input type="text" name='<?=$form_names['firstname'];?>' id='firstname' /><br>
Last Name: <input type="text" name='<?=$form_names['lastname'];?>' id='lastname' /><br>
Phone: <input type="tel" name='<?=$form_names['phone'];?>' id='phone' /><br>
Email: <input type="email" name="<?=$form_names['email'];?>" id="email" /><br>
Username: <input type="text" name='<?=$form_names['username'];?>' id='username' /><br>
Password: <input type="password"
name="<?=$form_names['password'];?>"
id="password"/><br>
Confirm password: <input type="password"
name="<?=$form_names['passwordconf'];?>"
id="confirmpwd" /><br>
<input type="button"
value="Register"
onclick="return regformhash(this.form,
this.form.<?=$form_names['firstname'];?>,
this.form.<?=$form_names['lastname'];?>,
this.form.<?=$form_names['phone'];?>,
this.form.<?=$form_names['username'];?>,
this.form.<?=$form_names['email'];?>,
this.form.<?=$form_names['password'];?>,
this.form.<?=$form_names['passwordconf'];?>);" />
</form>
</body>
I have included a hidden field with a name/value pair token, as well as random tokens for each name field. The tokens all work as intended, so the issue isn't in generating them. There is also a Javascript file that validates form entry, I don't know if it is relevant, but here is the js validation:
function regformhash(form, firstname, lastname, phone, username, email, password, confirmpwd) {
// Check each field has a value
if (firstname.value == '' || lastname.value == '' || phone.value == '' || email.value == '' || password.value == '' || confirmpwd.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the First Name
re = /^[A-Za-z\s]+$/;
if(!re.test(form.firstname.value)) {
alert("First Name must contain only upper and lower case letters. Please try again");
form.firstname.focus();
return false;
}
// Check the Last Name
re = /^[A-Za-z\s]+$/;
if(!re.test(form.lastname.value)) {
alert("Last Name must contain only upper and lower case letters. Please try again");
form.lastname.focus();
return false;
}
// Check the Phone Number
re = /\d{3}[\-]\d{3}[\-]\d{4}/;
if(!re.test(form.phone.value)) {
alert("Phone Number must be formatted as follows, xxx-xxx-xxxx or (xxx) xxx-xxxx. Please try again");
form.phone.focus();
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 != confirmpwd.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 = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
confirmpwd.value = "";
// Finally submit the form.
form.submit();
return true;
}
I don't know if the parameter names need to match up with the form names, they didn't all before and it worked.
Finally, the "Invalid or Unexpected Token" error was pointing to the closing </body>, if that helps as well.
Update:
I'm going to go more in depth about how this particular CSRF is working for this particular form. The form has an include to another php file, called register.inc.php, that does a series of sanitizations when adding data to the database, but I decided to also use it for the CSRF check. Here is the base code that relates to the CSRF (note, I haven't added the sanitization functions inside of the if statement yet, I'm trying to get the form to work without it before I add it in. I have a comment where it will eventually go):
include 'csrf.class.php';
require 'Sessions/session.class.php';
$session = new session();
// Set to true if using https
$session->start_session('_s', false);
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('firstname','lastname','phone','email', 'username', 'password','passwordconf'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
// Add Sanitization function here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
Here is the csrf.class.php that is being referenced here:
<?php
class csrf{
public function get_token_id() {
if(isset($_SESSION['token_id'])) {
return $_SESSION['token_id'];
} else {
$token_id = $this->random(10);
$_SESSION['token_id'] = $token_id;
return $token_id;
}
}
public function get_token() {
if(isset($_SESSION['token_value'])) {
return $_SESSION['token_value'];
} else {
$token = hash('sha512', $this->random(500));
$_SESSION['token_value'] = $token;
return $token;
}
}
public function check_valid($method) {
if($method == 'post' || $method == 'get') {
$post = $_POST;
$get = $_GET;
if(isset(${$method}[$this->get_token_id()]) && (${$method}[$this->get_token_id()] == $this->get_token())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public function form_names($names, $regenerate) {
$values = array();
foreach ($names as $n) {
if($regenerate == true) {
unset($_SESSION[$n]);
}
$s = isset($_SESSION[$n]) ? $_SESSION[$n] : $this->random(10);
$_SESSION[$n] = $s;
$values[$n] = $s;
}
return $values;
}
private function random($len) {
if (function_exists('openssl_random_pseudo_bytes')) {
$byteLen = intval(($len / 2) + 1);
$return = substr(bin2hex(openssl_random_pseudo_bytes($byteLen)), 0, $len);
} elseif (#is_readable('/dev/urandom')) {
$f=fopen('/dev/urandom', 'r');
$urandom=fread($f, $len);
fclose($f);
$return = '';
}
if (empty($return)) {
for ($i=0;$i<$len;++$i) {
if (!isset($urandom)) {
if ($i%2==0) {
mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
}
$rand=48+mt_rand()%64;
} else {
$rand=48+ord($urandom[$i])%64;
}
if ($rand>57)
$rand+=7;
if ($rand>90)
$rand+=6;
if ($rand==123) $rand=52;
if ($rand==124) $rand=53;
$return.=chr($rand);
}
}
return $return;
}
}
When the form is submitted, it saves the CSRF tokens from the form in a Session and compares it to the Tokens in the Post value. If the two match, then it continues with the code. Here is the site I used to create the CSRF protection, Prevent CSRF.

Jquery - fill input if user exist

I'm trying to fill a form if I find that the name and the firstname input by the user already exist in my database.
For the moment, I would like to check if the name and the firstname already exist in the database but my javascript program doesn't work. It's seems that the part..." "$.post("../modules/verifier_staff.php",{ nom: ..." is not correct.
Then I would like to fill my form with the data that my database give (array).
Can somenone help me to find my mistakes and to tell me how I can use the data i receive from database to fill my form?
$(document).ready(function(){
var form_nom = $("#staff_nom");
var form_prenom = $("#staff_prenom");
$(form_nom).change(function() {
checkvariable();
});
$(form_prenom).change(function() {
checkvariable();
});
function checkvariable(){
if((form_nom.val().length >0)&&(form_prenom.val().length>0)){
prenom_staff = form_prenom.val();
nom_staff = form_nom.val();
//alert(nom_staff);
$.post("../modules/verifier_staff.php",{ nom: nom_staff, prenom: prenom_staff},
function(data){
if(data)
{
alert('ok');
}
else alert('nok');
});
}
}
});
var form_nom = $("#staff_nom");
var form_prenom = $("#staff_prenom");
$(form_nom).change(function() {
checkvariable(form_nom,form_prenom); //pass arguments into the function
});
$(form_prenom).change(function() {
checkvariable(form_nom,form_prenom);
});
function checkvariable(form_nom,form_prenom){ //innclude argument in function definition
//......
}
thank for your help. Yes I'm sure that the path is correct.
Here is my code from ../modules/verifier_staff.php
<?php
include('../inc/settings.php');
include('../inc/includes.php');
//$_POST['nom']='Doe';
//$_POST['prenom']='John';
$nom=$_POST['nom'];
$prenom=$_POST['prenom'];
$Dbcon = new Db;
$personne_manager = new PersonneManager($Dbcon->dbh);
$personne = $personne_manager->get(array('conditions'=> array('nom' => strtolower($nom),'prenom' => strtolower($prenom))));
if($personne)
{
$result = true;
}
else
{
$result = false;
}
return $result;
?>
this part works well (I tested it) so I think the problem come from my javascript code. I'm a newbie in javascript/jquery.

Javascript Email Validation Specific Domain with PHP data

There is something wrong in this line:
var reg = /^[a-z.]+'#'+javaScriptVar$/;
but I don't know how to correctly write this. The current code would make "Please enter Email Address" appear every time. Here are the codes:
<?
$em=$_POST['myemail'];
$ar=split("#",$em);
?>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("User Name must be filled out");
return false;
}
if (document.forms["myForm"]["email"].value.length == 0) {
alert("Please enter Email Address");
return false;
} else {
var javaScriptVar = "<?php echo $ar[1]; ?>";
var reg = /^[a-z.]+'#'+javaScriptVar$/;
if (!reg.test(document.forms["myForm"]["email"].value)) {
alert("Please Enter Correct Email Domain");
return false;
}
}
}
You seem to be trying to include an # in your regex to check for url validation. Since there are no quotes used around your regex, specifying it like +'#'+ will not work.
Change it to:
/^[a-z.]#javaScriptVar$/
EDIT:
I think you are using the wrong regex to validate the url. Try this:
/^[a-zA-Z0-9]+[#][a-zA-Z0-9]+.{1}[a-z]{3}$/

javascript onBlur not working, and how to connect javascript files

I have two javascript files that I am using to validate an email address.
validate.js:
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (emailFilter.test(email.value)) {
//alert('Please provide a valid email address');
//email.focus;
return true;
}
else{
return false
}
}
navigation.js EDIT:
$(document).ready(function() {
//ADDED IMPORTS
var imported = document.createElement('script');
imported.src = 'lib/validation.js';
document.head.appendChild(imported);
console.log("DOCUMENT IS READY!");
var viewsWrapper = $("#views-wrapper");
var loginButton = $("#login-button");
var registerButton = $("#register-button");
// Login Link
// TODO: Unclear if needed
$("ul li.login").click(function() {
$.get('/login', function(data) {
viewsWrapper.html(data);
});
});
$('#usernamefield').blur(function() {
var sEmail = $('#usernamefield').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (checkEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
...(more code follows but not relevant)
I am also using this jade template:
login.jade:
form(action="")
key EMAIL
input(type="text", name="username", id="usernamefield")
p hello world
br
key PASSWORD
input(type="text", name="password", id="passwordfield")
p hello world
br
input(type="submit", name="loginButton", id="login-button", value="LOGIN")
My issue is that when I input something into my email field, I do not get an alert message in any case. Am I allowed to just have to separate javascript files and call the methods I defined in validate.js within navigation.js? I tried putting the validate.js code in navigation.js, but even then it did not work. I would like to keep the files separate. Am I missing something obvious? I want it so that once the user inputs the email, and leaves the field, a message should appear warning if the email is valid or not.
Your help is appreciated.
Is it the blur Event or the checkEmail the problem? try to put a alert() or console.log() just after your blur (and make sure to lose focus on your input). Seperate file shouldn't be a problem. And also have you check for errors in your console ?
JavaScript string has no "value" field
After
var sEmail = $('#username').val();
sEmail becomes a string.
You are passing this string to checkEmail method and try to get "value" from a string:
if(!emailFilter.test(email.value)) {//...}
Replace to
if (!emailFilter.test(email)) {//...}
You are already sending the value of email into checkemail function. So in checkEmail function in validate.js remove email.value in second line of function checkEmail
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
//alert('Please provide a valid email address');
email.focus;
return false;
}
}

Check for Valid Email with jQuery

I am trying to use jQuery to see if a user has entered a valid email address into my text box.
Basically, I want the submit button to remain disabled by default, but on each keyup I want to see if the email address is valid, then I want to enable the button. If the user enters a valid email but then deletes parts so that it becomes invalid again (i.e. the # symbol) I want the submit button to become disabled again.
I have a partially working script here. My check or the # symbol works well, but I am having a hard time checking for .com, .co, .net, .org, .edu etc... For some reason, the button keeps enabling even though I have not entered a valid "ending" to the email.
For example "emailco#" is recognized as a valid email. Here is my script:
<script>
$(document).ready(function() {
$('#email').bind('keyup', function(e) {
var email = document.getElementById("email");
if (email.value.search("#") != -1) {
if (
(email.value.search(".com") != -1)||
(email.value.search(".co") != -1)||
(email.value.search(".org") != -1)||
(email.value.search(".net") != -1)||
(email.value.search(".gov") != -1)||
(email.value.search(".biz") != -1)||
(email.value.search(".me") != -1)||
(email.value.search(".edu") != -1)) {
document.getElementById("email_go").disabled = false;
}
else {
document.getElementById("email_go").disabled = true;
}
}
else {
document.getElementById("email_go").disabled = true;
}
});
});
</script>
Just use regex:
if (email.value.search("#") != -1) {
if (/(.+)#(.+)\.(com|edu|org|etc)$/.test(email.value))
}
var email = $('#email').val();
var pattern = ".+\\##.+\\..+";
var valid = email.match(pattern);
if (valid == null) {
alert("Not Valid");
return;
}
else{
alert("Valid");
return;
}
Try this. Of course, this is just a basic example and I'm sure that email addresses nowadays can end in more than just what's specified in the array below. But, still... you get the idea...
// Split the email to see if there's an "#" character
var split = email.split('#');
var split_count = split.length;
// If there is, then split the second string by a "."
if (split_count == 2) {
var domain = split[1].split('.');
var domain_count = domain.length;
if (domain_count == 2) {
// Store all of the accepted values for email endings
var endings = ['org', 'com', 'net', 'edu', 'info', 'biz', 'me'];
var result = $.inArray(domain[1], endings);
// If the final 3 chars of the string are in the array, then proceed
if (result > 0) {
}
}
}
I use this Regex Code to test email format using jQuery:
var email = $('.email').val();
if(email.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/))
{
alert('OK');
}

Categories

Resources