JavaScript Text Only Input

This function can be used on the onkeypress event of a HTML input box to only allow entry of text charactes: A-Z, a-z, dash, space, and backspace.

Usage:

<input type="text" id="name" onkeypress="return textonly(event);" /> 

Javascript:

function textonly(e){
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
//alert('Character was ' + character);
    //alert(code);
    //if (code == 8) return true;
    var AllowRegex  = /^[\ba-zA-Z\s-]$/;
    if (AllowRegex.test(character)) return true;    
    return false;
}

Advertisements

Javascript Validate South African Identity Number

function validateSAID(elementID)
{
var SAIDRegEx = /^(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
if (SAIDRegEx.test(document.getElementById(elementID).value)) return true; return false;
}

Take a look at this blog post for more information about SA ID number structure and validation.

Javascript key codes

http://webonweboff.com/tips/js/event_key_codes.aspx

JavaScript Numeric Only Input

Use the following JavaScript function to only allow numeric (0-9) input and backspace input in a web form text field.

JavaScript:

function numbersonly(e) {
var unicode=e.charCode? e.charCode : e.keyCode;
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
if (unicode<48||unicode>57) //if not a number return false //disable key press
}}

Usage:

<input onkeypress=”return numbersonly(event);” name=”VAT_Number”>

To allow for tabbing change (unicode!=8) to (unicode!=8 && unicode!=9)

Simple Javascript CAPTCHA

Simple CAPTCHA using Javascript. The page collecting the form information should collect from forms only. eg. in ASP: request.forms(“name”)

Click here to download the code: BotBoot1.html

Validate SA Cell Number with Javascript

function validate(){
var MobileNumber = document.getElementById(“MobileNumber”).value;
var MobileNumberRegEx = /^\+27[78][23467][0-9]{7}/;
if (MobileNumberRegEx.test(MobileNumber)) {
return true;
}else{
alert(“Please enter a valid South African mobile phone number\nin the following format: +27820000000”);
return false;
}
}