Membership plugin: Changing username field to only accept letters and numbers

7 posts by 4 authors in: Forums > CMS Builder: Plugins & Add-ons
Last Post: July 11, 2016   (RSS)

It is possible to change the username field so it only accepts letters and numbers? No special characters or spaces should be allowed.

By Chris - February 29, 2016

Hi superhappybunnycat,

You can enforce this within CMS Builder by turning on system field editing (Admin > Section Editors > User Accounts, Advanced Commands... (near the bottom of the page)), then setting up the Allowed Content input validation settings for the username field. Let me know if the attached screenshot doesn't make it clear how to set it up and how it works.

If you have a front-end form which allows people to sign up and/or change their usernames, you'll need to add custom logic into it. If that's the case, please post the source code of your form and we can see if we can help from there.

Hope this helps!

All the best,
Chris
Attachments:

charset.png 100K

Updating that setting in the CMS panel was easy. I'm not sure what I need to add into my form so that it doesn't allow the special characters to be entered however. My sign up form is below

<?php 

#$_STRIPE_TEST = 1;
include_once("includes.php");
$gr_api = new GetResponse($_GET_RESPONSE_API_KEY);
error_reporting(0);

$title = “My website“;

  // load viewer library
  $libraryPath = 'cms/lib/viewer_functions.php';
  $dirsToCheck = array('/home/public_html/','','../','../../','../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }
  if (!@$GLOBALS['WEBSITE_MEMBERSHIP_PLUGIN']) { die("You must activate the Website Membership plugin before you can access this page."); }

 // load records from 'membership_plans'
  list($membership_plansRecords, $membership_plansMetaData) = getRecords(array(
    'tableName'   => 'membership_plans',
    'loadUploads' => true,
    'allowSearch' => false,
  ));

  //
  $useUsernames   = true; // Set this to false to disallow usernames, email will be used as username instead


if (@$CURRENT_USER) 
rpage2($title, <<<EOF
<div class="container">
<div class="cart-checkout-content">
<div style="error">
You are already signed up! <a href='/'>Click here to continue</a>.
<br/><br><br><br><br><br><br><br>
</div>
</div>
</div>

EOF
);

if(@$_GET["done"])
rpage2($title, <<<EOF
<div class="container">
<div class="cart-checkout-content">
<div style="error">
Thanks, We've created an account for you and emailed you your password.<br/><br/>
If you don't receive an email from us within a few minutes check your spam filter for messages from {$fromEmail}<br/><br/>
<a href='login.php'>Click here to login</a>.
<br/><br><br><br><br><br><br><br>
</div>
</div>
</div>

EOF
);

# Submission in iframe
if(@$_POST["go"])
{
$uname = coalesce( $_POST['username'], $_POST['stripeEmail'] );
$email = $_POST['stripeEmail'];
if(mysql_count(accountsTable(), array('username' => $uname)))
rpage($title, "<h3>User $uname already exists");
if(mysql_count(accountsTable(), array('email' => $email)))
rpage($title, "<h3>E-mail $email already exists");

list($ok, $err, $jj) = stripe_go();

if(!$ok)
rpage($title, "<h3>Stripe error: $err</h3>");

list($sub) = array_reverse($jj["subscriptions"]["data"]);
$sid = mysql_escape(@$jj["id"]);


      // generate password
      $passwordText = wsm_generatePassword();
      $passwordHash = getPasswordDigest($passwordText);

      //
      $colsToValues = array();
      $colsToValues['createdDate=']     = 'NOW()';
      $colsToValues['updatedDate=']     = 'NOW()';
      $colsToValues['createdByUserNum'] = 0;
      $colsToValues['updatedByUserNum'] = 0;

      // fields defined by form:
      //$colsToValues['agree_tos']      = $_REQUEST['agree_tos'];
      $colsToValues['fullname']         = $_POST['fullname'];
      $colsToValues['email']            = $email;
      $colsToValues['username']         = $uname; // email is saved as username if usernames not supported
      $colsToValues['password']         = $passwordHash;
      $colsToValues['selectedplan']     = $_POST['planname1'];
      $colsToValues['selected_plan_id'] = plan_id2num($_POST['planname']);
      $colsToValues['stripe_id'] = $sid;
      $test = mysql_escape(@$_STRIPE_TEST);
      $colsToValues['stripe_test'] = $test;
  $colsToValues['campaign_id'] = $_GET_RESPONSE_API_CAMPAIGNS[$colsToValues['selected_plan_id']];


        // ... add more form fields here by copying the above line!
       $userNum = mysql_insert(accountsTable(), $colsToValues, true);


/*
$email = mysql_escape(@$jj["email"]);
$uid = 0 + $userNum;
$plan = mysql_escape(@$sub["plan"]["id"]);
$stime = mysql_escape(@$sub["plan"]["created"]);
$test = mysql_escape(@$_STRIPE_TEST);
$data = mysql_escape(json_encode($jj));
mysqlStrictMode(false);

       if(!mysql_query("INSERT INTO `stripe` (id, uid, email, plan, stime, test) 
VALUES('$sid', '$uid', '$email', '$plan', '$stime', '$test')"))
rpage($title, "MySQL error" . mysql_error());
*/

      // set access rights for CMS so new users can access some CMS sections
      $setAccessRights = false; // set to true and set access tables below to use this
      if ($setAccessRights && accountsTable() == "accounts") { // this is only relevant if you're adding users to the CMS accounts table

        // NOTE: You can repeat this block to grant access to multiple sections
        mysql_insert('_accesslist', array(
          'userNum'      => $userNum,
          'tableName'    => '_sample',   // insert tablename you want to grant access to, or 'all' for all sections
          'accessLevel'  => '0',         // access level allowed: 0=none, 6=author, 9=editor
          'maxRecords'   => '',          // max listings allowed (leave blank for unlimited)
          'randomSaveId' => '123456789', // ignore - for internal use
        ));
}
$gr_api->addContact([
'name' => $colsToValues['fullname'],
'email' => $colsToValues['email'],
'campaign' => ['campaignId' => $colsToValues['campaign_id']],
]);
      // send message
      list($mailErrors, $fromEmail) = wsm_sendSignupEmail($userNum, $passwordText);
      if ($mailErrors) { alert("Mail Error: $mailErrors"); }

    // redirect to profile page after after signing up
     setPrefixedCookie('lastUrl', $GLOBALS['WEBSITE_LOGIN_PROFILE_URL']);
rpage($title, <<<EOF
Thanks, We've created an account for you and emailed you your password.<br/><br/>
If you don't receive an email from us within a few minutes check your spam filter for messages from {$fromEmail}<br/><br/>
<a href='login.php'>Click here to login</a>.
EOF
);


    
}

$ch = "checked";
$gplan = $_GET["plan"];
if(!$gplan)
list($gplan) = array_keys($_PLANS);
foreach($_PLANS as $pid => $pname)
{
if($pid == $upid)
continue;
$pp = stripe_pdata($pid);
#html_dump($pp);
$psum = $pp["amount"] / 100;
$interval = $pp["interval"];

$ch = ($pid == $gplan ? "checked" : "");
$buttons .= <<<EOF
<input id="plan$pid" type="radio" name="plan" value="$pid" $ch>
<label for="plan$pid" class="payment-method">
<i class="icon icon-office-51 pull-left"></i>$pname \$$psum/$interval
</label>
EOF;
$plancheck .= <<<EOF
if(pid == '$pid')
{
planname1 = '$pname';
planname = '$pname \$$psum/$interval';
sum = $psum * 100;
}

EOF;
}

$SCODE = stripe_pcode("basic");

$pkey = $_STRIPE["publishable_key"];

$eds = date("r", time() + 86400 * 10);
$BLOCK2 = <<<EOF
<div id="BLOCK2" class="tab-pane fade active in" style="display: none">



<div class="col-sm-12">
<div class="heading-block align-center">
<h3 class="post-title">Create your account</h3>
</div>

<p>Please enter your details below so we can create an account for you that will be used to access the site.</p>



<div class="col-sm-6 col-sm-offset-3">
<div class="align-center">
<div class="row">

<fieldset class="form-group form billing-details-form">
<!--
<label>Username:</label>
-->
<span id="error-username" style="color: #ff5555; font-size: 18px;"></span>
<input input type="text" name="username" placeholder="Username" value="">
</fieldset>


<fieldset class="form-group">
<!--
<label>Full name:</label>
-->
<span id="error-fullname" style="color: #ff5555; font-size: 18px;"></span>
<input type="text" name="fullname" placeholder="Name" value="">
</fieldset>

</div>
</div>
</div>


<div class="cart-checkout-navigation-controls col-sm-12">
<p><br>
<a href="#" class="prev btn btn-outline-color" onClick="selp(1)">Back</a>
<a href="#" class="btn btn-solid pull-right" 
onClick="
var f = document.getElementById('REGOFORM');
if(!f.username.value)
{
    selp(2);
    document.getElementById('error-username').innerHTML = 'Please enter a username';
    f.username.focus();
    return(false);
}

if(!f.fullname.value)
{
    selp(2);
    document.getElementById('error-fullname').innerHTML = 'Please enter your name';
    f.fullname.focus();
    return(false);
}

var planname = '';
var planname1 = '';
var sum = 0;
var pid = planvalue();
//document.cookie = 'selplan = ' + pid + '; expires=$eds; path=/';

document.getElementById('SUMMARY_USER').innerHTML = f.username.value;
document.getElementById('SUMMARY_NAME').innerHTML = f.fullname.value;
$plancheck
document.getElementById('SUMMARY_PLAN').innerHTML = planname;


var sform = document.getElementById('stripe-form');
sform.username.value=f.username.value;
sform.fullname.value=f.fullname.value;
sform.planname.value=pid;
sform.planname1.value=planname1;

var but = document.getElementById('stripe-button');
but.setAttribute('data-amount', sum);
but.setAttribute('data-name', planname);
but.setAttribute('data-description', planname);

selp(3);


return(false);
">Continue</a>
</p>
</div>




</div>

</div>

EOF;

$FH = 50;
$BLOCK3 = <<<EOF
<div id="BLOCK3" class="tab-pane fade active in" style="display: none">



<div class="col-sm-12">
<div class="heading-block align-center">
<h3 class="post-title">Your summary</h3>
</div>

Username: 
<b><span id="SUMMARY_USER"></span></b>
<br>
Full name:
<b><span id="SUMMARY_NAME"></span></b>
<br>
Your selected plan: 
<b><span id="SUMMARY_PLAN"></span></b>
<br>
<br>



<form action="$MYPHP" method="post" id="stripe-form">
<input type=hidden name="go" value=1>
<input type=hidden name="planname">
<input type=hidden name="planname1">
<input type=hidden name="username">
<input type=hidden name="fullname">

<div class="cart-checkout-navigation-controls">
<p><br>
<a href="#" class="prev btn btn-outline-color" onClick="selp(2)">Back</a>
        <input id="stripe-button"
class="cart-submit btn btn-solid pull-right"
            type="submit" 
            value="Pay with Card"
            data-key="$pkey"
            data-amount="0"
            data-currency="usd"
            data-name="UNKNOWN"
            data-description="UNKNOWN"
        />
</p>
</div>


</form>


<br>
<br>
</div>

EOF;
  
$top = <<<EOF
<div class="cart-checkout">
<div class="cart-checkout-navigation">
<ul class="cart-checkout-navigation-list" qrole="tablist">
<li id=MLI1 class="active"><span class="cart-checkout-navigation-list-item-link">Select your plan</span></li>
<li id=MLI2><span class="cart-checkout-navigation-list-item-link">Create your account</span></li>
<li id=MLI3><span  class="cart-checkout-navigation-list-item-link">Confirm your order</span></li>
</ul>
</div>
</div>
EOF;

rheader("Registration", $top);
print <<<EOF
        <script src="https://checkout.stripe.com/v2/checkout.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script language="javascript">
function selp(num)
{
if(num == 1)
{
document.getElementById('MLI1').className = 'active';
document.getElementById('MLI2').className = '';
document.getElementById('MLI3').className = '';
document.getElementById('BLOCK1').style.display = 'block';
document.getElementById('BLOCK2').style.display = 'none';
document.getElementById('BLOCK3').style.display = 'none';
}
else if(num == 2)
{
document.getElementById('MLI1').className = '';
document.getElementById('MLI3').className = '';
document.getElementById('MLI2').className = 'active';
document.getElementById('BLOCK1').style.display = 'none';
document.getElementById('BLOCK2').style.display = 'block';
document.getElementById('BLOCK3').style.display = 'none';
}
else if(num == 3)
{
document.getElementById('MLI1').className = '';
document.getElementById('MLI2').className = '';
document.getElementById('MLI3').className = 'active';
document.getElementById('BLOCK1').style.display = 'none';
document.getElementById('BLOCK2').style.display = 'none';
document.getElementById('BLOCK3').style.display = 'block';
}
}

        $(document).ready(function() {
            $('#stripe-button').on('click', function(event) {
                event.preventDefault();
                var \$button = $(this),
                    \$form = \$button.parents('form');
                var opts = $.extend({}, \$button.data(), {
                    token: function(result) {
                        \$form.append($('<input>').attr({ type: 'hidden', name: 'stripeToken', value: result.id }));
                        \$form.append($('<input>').attr({ type: 'hidden', name: 'stripeEmail', value: result.email }));
\$form.submit();
                    }
                });
                StripeCheckout.open(opts);
            });
        });
function planvalue()
{
p = document.querySelector('input[name="plan"]:checked').value;
if(typeof(p) == 'undefined' || p == '' || p == 'undefined')
p = document.getElementbyId('REGOFORM').plan.value;

if(typeof(p) == 'undefined' || p == '' || p == 'undefined')
alert("Can't get plan ID");
return(p);
}
</script>

<div class="">
<div class="cart-checkout-content tab-content">

<form id=REGOFORM method="post" class="form payment-method-form" onSubmit="return(false)">
  
<input type="hidden" name="save" value="1" />

<!-- PAGE 1 -->
<div id="BLOCK1" class="tab-pane fade active in">


<div class="col-sm-12">
<div class="heading-block align-center">
<h3 class="post-title">Select your plan</h3>
</div>
$buttons
<div class="cart-checkout-navigation-controls">
<a href="#" onClick="selp(2)" class="next btn btn-solid">Continue</a>
</div>

</div>    
</div>




<!-- END OF PAGE 1 -->
            

<!-- PAGE 2 -->
$BLOCK2

</form>
<!-- END OF PAGE 2 -->
                

<!-- PAGE 3 -->
$BLOCK3
<!-- END OF PAGE 3 -->
</div>


</div>            
</div>
EOF;

rfooter();

By Damon - March 28, 2016

Hi,

Based on the Website Membership code generator code for user-signup.php, you could take the default error checking like this:

    if ($useUsernames) {
      if     (!@$_REQUEST['username'])                     { $errorsAndAlerts .= "You must choose a username!<br/>\n"; }
      elseif (preg_match("/\s+/", @$_REQUEST['username'])) { $errorsAndAlerts .= "Username cannot contain spaces!<br/>\n"; }
      elseif ($usernameAlreadyInUse)                       { $errorsAndAlerts .= "That username is already in use, please choose another!<br/>\n"; }
    }

and change to this using the PHP cctype_alnum function that checks for alphanumeric character:

    if ($useUsernames) {
      if     (!@$_REQUEST['username'])                     { $errorsAndAlerts .= "You must choose a username!<br/>\n"; }
    //elseif (preg_match("/\s+/", @$_REQUEST['username'])) { $errorsAndAlerts .= "Username cannot contain spaces!<br/>\n"; }
      elseif (!ctype_alnum(@$_REQUEST['username']))        { $errorsAndAlerts .= "Username cannot contain spaces or special characters!<br/>\n"; }
      elseif ($usernameAlreadyInUse)                       { $errorsAndAlerts .= "That username is already in use, please choose another!<br/>\n"; }
    }


Try that out. I have working on my test installation.

Cheers,
Damon Edis - interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/

By Damon - June 28, 2016

Hi,

When there is this much code on a page, I suggest starting with a stripped down version on a separate page for debugging.

Start with just the code from the code generator for the "Signup / Create an account":
Admin > Code Generator > Website Membership             

Get this working by itself. Then add in all the error checking needed and confirm that works.

Then add in the rest of the code from your page above, small amounts at a time and retesting.

Cheers,
Damon Edis - interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/

By Twocans - July 11, 2016

Brilliant!