Text Field
Sketch code
let gui;
function setup() {
let p5canvas = createCanvas(640, 200); p5canvas.parent('sketch');
gui = GUI.get(p5canvas);
gui.scheme('purple').textSize(16);
gui.label('lbl0', 20, 25, 200, 40).text(`Text to capitalize`).opaque();
gui.label('lbl1', 20, 85, 200, 40).text(`Any integer number`).opaque();
gui.label('lbl2', 20, 145, 200, 40).text(`Any positive\ndecimal number`).opaque();
gui.label('lbl3', 480, 90, 100, 80).textSize(14).text(`Use UP / DOWN\narrows to move\nbetween text\nfields.`).opaque().scheme('red');
gui.textfield('txf0', 240, 30, 370, 30).index(0, 5)
.validation(capitalizeName);
gui.textfield('txf1', 240, 90, 220, 30).index(5, 5)
.validation(validateInteger);
gui.textfield('txf2', 240, 150, 220, 30).index(10, 5)
.validation(validateNumberRange(0, Number.MAX_VALUE));
}
function arrow(x, y, ang) {
push();
translate(x, y); rotate(ang);
fill(245, 160, 76); stroke(0); strokeWeight(1.05);
triangle(2, 3.5, 2, -3.5, 28, 0);
triangle(20, 7, 20, -7, 28, 0);
pop();
}
function draw() {
background(255, 210, 255);
push();
arrow(280, 60, Math.PI / 2);
arrow(310, 90, 3 * Math.PI / 2);
arrow(280, 120, Math.PI / 2);
arrow(310, 150, 3 * Math.PI / 2);
pop();
gui.draw();
}
// All validation functions must return an array. The first element
// is either true (valid) / false (invalid). The second element
// (optional) is the amended text to display.
function capitalizeName(str) {
if (!str) return [false];
if (str.length > 0) {
str = str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Convert mcdonald to McDonald
str = str.replace(/\bMc[a-z]*/g, function (txt) {
return 'Mc' + txt.charAt(2).toUpperCase() + txt.substr(3).toLowerCase();
});
}
return [true, str];
}
function validateInteger(txt) {
if (!txt) return [true, '']; // Accept empty field
let n = Number(txt); // Need to coerce txt to number
return [Number.isInteger(n)];
}
function validateNumberRange(low, high) {
return function (txt) {
if (!txt) return [true, '']; // Accept empty field
let n = Number(txt); // Need to coerce txt to number
return [Number.isFinite(n) && n >= low && n <= high];
}
}
Event information
The info
object contains the following fields -
Field | Description |
source |
A reference to the control that generated the event |
p5Event |
A reference to original event generated by p5.js |
value |
The text currently being displayed in the field. |