Validate user input for extra long words in textarea - javascript

I have a problem here with validating user's input in textarea.
A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.
Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page.
Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??
PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side

var STRING_MAX_LENGTH = 10;
var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );
$.each( array, function() {
if ( this.length >= STRING_MAX_LENGTH ) {
if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i . test( this ) ) {
alert( this + ' is an URL' );
} else {
alert( this + ' is not an URL' );
}
}
});
http://jsfiddle.net/vVYAp/

function validate()
{
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var wordLengthExpr = /\b[^\s]{50,}\b/;
var regex = new RegExp(expression);
var wordLengthRegex = new RegExp(wordLengthExpr);
var t = $("#myTextarea").val();
if (t.match(regex) || !t.match(wordLengthRegex))
{
//valid
}
else
{
//throw error
}
}

This is a two step process:
Determine if any words are too long.
If so, determine if they are valid URLs.
var validateWordLength = function (str) {
var maxLength = 50, // or whatever max length you want
reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
words = str.split(/\s+/),
i;
for (i = 0; i < words.length; i += 1) {
if (words[i].length > maxLength) {
// test for url
// but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
// testing for url may not be fruitful
if (!reURL.test(words[i])) {
return false;
}
}
}
return true;
};

try this
var value = Your text;
var result = value.replace(" ","");
if(value.length == result .length)
//not valid
else
//valid

You can get length of each word, and then can decide whether to allow the user or not -
var arr = text.split(' ');
$.each(arr,function(){
console.log(this.length);
// check valid word length
});
http://jsfiddle.net/mohammadAdil/cNZtn/

If you use the jQuery validate plugin you can add a method to it:
jQuery.validator.addMethod("samechars", function(value, element) {
return this.optional(element) || !/([a-z\d])\1\1/i.test(value);
}, "Invalid input");

If you want to use jQuery you can use the following:
$("form").submit(function(e){
var $textarea = $('#msg'),
maxWordLength = 20;
var value = $textarea.val().split(' '),
longWord = false;
for(var n = 0; n < value.length; n++) {
if(value[n].length >= maxWordLength)
longWord = true;
}
if(longWord) {
alert('Too long word');
return false;
}
});
Here is a fiddle:
http://jsfiddle.net/pJgyu/31286/

Related

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Javascript to verify specific String from textbox

Here what the textbox result looks like,
Please add the following DNS entries
144.68.238.87 name.domain
144.68.238.88 name.domain
144.68.238.89 name.domain
The goal is to validate name.domain by making sure that the user replace name.domain to server name on textbox before submit it. If the user doesn't replace name.domain with their server name, then it will send alert message and return false until user replace it correctly.
Here is my codes,
function DomainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('/n');
arrayOfLines.shift(); //use shift to skip the first line
for (i = 0; i < arrayOfLines.length; i++) {
//somewhere here need to split to get name.domain and then verify it
var domainName = arrayOfLines[i].split(" ", 2);
if(domainName.Equals("name.domain")
{
alert("You must replace name.domain to your new server name");
return false;
}
}
}
I am not sure if these are correct since I couldn't debug the javascript.
First issue I can see is that your character for the newline is incorrect. It should be \n not /n. Second issue I see is that i is a global variable, when it should be local. Third issue is that arrayOfLines[i].split(' ', 2); returns an array, but you are treating it like it returns a string on the next line if (domainName.Equals('name.domain').
With those corrections your code would look more like this:
function domainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('\n');
arrayOfLines.shift(); //use shift to skip the first line
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i].trim();
// Grab the second part of the split line, which represents the domain name
var parts = line.split(' ');
var domainName = parts[parts.length - 1];
if (!domainName || domainName === 'name.domain') {
alert("You must replace name.domain to your new server name");
return false;
}
}
}
As far as I can tell without testing, this should work as expected. The best way to test this though is with jsfiddle. Add your html and this script and call it to see if it produces the expected result.
Easiest way that I think
Suppose the id of textbox is domainTxt
src = document.getElementById("domainTxt");
if(verifyInput(src.value)){
//submit your form here
} else
{
return false;
}
function verifyInput(txtVal){
if(txtVal.indexOf("name.domain") >-1){
return false;
}else {
return true;
}
}

Validate variable javascript

I need to validate some user input with javascript. I need to check that their entry (value) is of the correct type (type).
I need my regex pattern to make sure values only contain numbers and nothing else, except measurment types can also contain decimal points.
What is the correct way to do this? My way seems like it may be, but i am guessing. In any case, something is wrong with my regular expression patterns as it is throwing the error stated in the code comment.
Here is my code:
function validateInput(value, type) {
console.log(value);
if(type === "Integer"){
var patt = new RegExp("^\D", i);
}
else if(type === "Measurement"){
var patt = new RegExp("^\D", i); //Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '2'
}
else{
return true;
}
if(patt.test(value)){
return false;
}
else{
return true;
}
}
function sendObs() {
RID = $("#oid").val();
console.log(RID);
var children = $("#abc").children();
var xmlString = "<root><rid>" + RID + "</rid>";
for(i=0; i < children.length; i++){
var value = children[i].children[0].value;
var type = children[i].children[0].id;
var validationResult = validateInput(value, type);
if(!validationResult){ //calling the validation method here
alert("invalid entry");
return;
}
var code = children[i].children[0].className;
xmlString += '<question><code>' + code + '</code><value>' + value + '</value></question>'
}
xmlString +='</root>'
console.log(xmlString);
data = $.parseXML(xmlString);
console.log(data);
//send it here
}
Instead of using regular expressions, you could just call parseInt() and parseFloat().
On top of converting your strings to workable numbers, both functions return NaN if the input is invalid.
number = parseFloat(string)
if (isNaN(number)) {
# `string` is invalid
}

how to convert first letter of an input box to upper case which also contains Numeric value using Javascript

I have an address field in my registration page which contains both numeric and letters, I want to change the first letter to upper case.
Can anyone give me some javascript code to do so..
for example.
1. wallmart street ..Output -> Wallmart street
2. 221,wallmart street.. Output -> 221,Wallmart street.
function foo(val)
{
return val.replace(/[a-zA-Z]/, function(letter) {
return letter.toUpperCase();
});
}
try this,
function changeCase(what)
{
var val
if(what!=null){val= what.value};
if(val!=null && val.length>0)
{
what.value=val.charAt(0).toUpperCase()+val.substring(1,val.length);
}
}
This function will take a string, change the first character occurrence to uppercase, and return the string.
String.prototype.capitalize = function(){
var self = this.split('');
for( var i=0; i < self.length; i++ ){
if( /^[a-zA-ZäöüßÄÖÜ]+$/.test(self[i]) ){
self[i] = self[i].toUpperCase();
break;
}
}
return self.join('');
}
Use like so.
var title = "1. wall street";
title = title.capitalize();

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

I'm looking for an example of how to capitalize the first letter of a string being entered into a text field. Normally, this is done on the entire field with a function, regex, OnBlur, OnChange, etc. I want to capitalize the first letter while the user is still typing.
For instance, if I'm typing the word "cat", the user should press 'c', and then by the time he presses 'a', the C should be capitalized in the field.
I think what I'm going for might be possible with keyup or keypress but I'm not sure where to start.
Anyone have an example for me?
Just use CSS.
.myclass
{
text-transform:capitalize;
}
This will simply transform you first letter of text:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
I answered this somewhere else . However, here are two function you might want to call on
keyup event.
To capitalize first word
function ucfirst(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
And to capitalize all words
function ucwords(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
As #Darrell Suggested
$('input[type="text"]').keyup(function(evt){
// force: true to lower case all letter except first
var cp_value= ucfirst($(this).val(),true) ;
// to capitalize all words
//var cp_value= ucwords($(this).val(),true) ;
$(this).val(cp_value );
});
Hope this is helpful
Cheers :)
$('input[type="text"]').keyup(function(evt){
var txt = $(this).val();
// Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
$(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.
JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":
Add to your script:
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
Then just attach capitalize() to any selector:
$('#myform input').capitalize();
I used the code of #Spajus and wrote a more extended jQuery plugin.
I wrote these four jQuery functions:
upperFirstAll() to capitalize ALL words in an inputfield
upperFirst() to capitalize only the FIRST word
upperCase() to convert the hole text to upper case
lowerCase() to convert the hole text to lower case
You can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()
My complete jQuery plugin:
(function ($) {
$.fn.extend({
// With every keystroke capitalize first letter of ALL words in the text
upperFirstAll: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// With every keystroke capitalize first letter of the FIRST word in the text
upperFirst: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to lowercase
lowerCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase());
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to uppercase
upperCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toUpperCase());
box.setSelectionRange(start, end);
});
return this;
}
});
}(jQuery));
Groetjes :)
My personal favorite when using jQuery is short and sweet:
function capitalize(word) {
return $.camelCase("-" + word);
}
There's a jQuery plugin that does this too. I'll call it... jCap.js
$.fn.extend($, {
capitalize: function() {
return $.camelCase("-"+arguments[0]);
}
});
$("#test").keyup(
function () {
this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
}
);
Slight update to the code above to force the string to lower before Capitaliing the first letter.
(Both use Jquery syntax)
function CapitaliseFirstLetter(elemId) {
var txt = $("#" + elemId).val().toLowerCase();
$("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase(); }));
}
In addition a function to Capitalise the WHOLE string:
function CapitaliseAllText(elemId) {
var txt = $("#" + elemId).val();
$("#" + elemId).val(txt.toUpperCase());
}
Syntax to use on a textbox's click event:
onClick="CapitaliseFirstLetter('myTextboxId'); return false"
this will help you in - convert first letter of each word to uppercase
<script>
/* convert First Letter UpperCase */
$('#txtField').on('keyup', function (e) {
var txt = $(this).val();
$(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
return $1.toUpperCase( );
}));
});
</script>
Example : this is a title case sentence -> This Is A Title Case Sentence
My appologies. The syntax was off due to me being in a hurry and sloppy. Here you go...
$('#tester').live("keyup", function (evt)
{
var txt = $(this).val();
txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
$(this).val(txt);
});
Simple but works. You would def want to make this more general and plug and playable. This is just to offer another idea, with less code. My philosophy with coding, is making it as general as possible, and with as less code as possible.
Hope this helps. Happy coding! :)
It's very cool you can capitalize Only the first letter of an input field With this one.. If any one know how to capitalize Like CSS text-transform:capitalize, Please Reply ..
Here You go..
$('input-field').keyup(function(event) {
$(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1)));
});
If using Bootstrap, add:
class="text-capitalize"
For example:
<input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">
A turkish one. If someone is still interested.
$('input[type="text"]').keyup(function() {
$(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])|\s+([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])/g, function ($1) {
if ($1 == "i")
return "İ";
else if ($1 == " i")
return " İ";
return $1.toUpperCase();
}));
});
With Javascript you can use:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
If by chance you're generating your web page with PHP you can also use:
<?=ucfirst($your_text)?>
Jquery or Javascipt doesn't provide a built-in method to achieve this.
CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.
If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/\s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.
CSS
#field {
text-transform: capitalize;
}
jQuery
$('#field').keyup(function() {
var caps = jQuery('#field').val();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
jQuery('#field').val(caps);
});
A solution that accept exceptions(passed by parameters):
Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);
(function($) {
$.fn.maskOwnName = function(not_capitalize) {
not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart,
end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
}
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
}
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
}
})(jQuery);
.first-character{
font-weight:bold;
color:#F00;
text-transform:capitalize;
}
.capital-text{
text-transform:uppercase;
}
My attempt.
Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names.
Happens on Blur as to not cause annoyances on phones.
Although left in selection start/end so if changed to keyup maybe useful still.
Should work on phones but have not tried.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,

Categories

Resources