Often it's required to validate a text box on html form before submission. specially we want to make sure user does enter something in particular textbox.
it becomes extremely tedious when you have many textboxes lying on a page with so many other controls. Many of them does not require any validation.
My 3 javascript functions does that very efficiently. In case if I want to add any new textbox in my validation all I have to do is modify one string array.Just add that textbox's ID in that array and you are done.
Besides I am using a customized trim function with regular expression to trim the entered text from left and right.
Here is my code...
In my example I am validating these textboxes. 'txtFName,txtLname,txtAge,txtDOB'
Just check the array elementIDs in globalValidate() function. it's key to validate any textbox.
function jstrim(str) { var s = new String(); s = str; return s.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function validateInput(inputID) { var bret = false; try { bret = (jstrim(document.getElementById(inputID).value) != ""); } catch(ex) { //alert("Input Validation Error for ID ' " + inputID + "' , " +ex.description); bret = false; } return bret; } function globalValidate() {
// modify this IDs to include an html textbox var elementIDs = "txtFName,txtLname,txtAge,txtDOB";
var valRes = true; var arrID = elementIDs.split(","); var i=0; for(i=0;i { valRes = validateInput(arrID[i]); if(!valRes) { //alert("Please enter some text for ID '" + arrID[i] + "':" + valRes); document.getElementById( arrID[i]).focus(); break; } } //alert("validation result: " + valRes); return valRes; }
remaining logic is very easy to understand, Importantly , if any of the textboxes is empty it will get the focus and user does not have to look for where to go to enter the text. You can customize your alert message or even modify the validation logic as you like...
Below is the attachment that you can test directly.
javascript is very powerful.
AttachmentsJavascript general function for any textbox validation (28123-301636-jsTextvalidation.rar)
|
No responses found. Be the first to respond and make money from revenue sharing program.
|